Data Structure & Algorithm: Level-1 Problem #12. Nim Game

Nim Game is a mathematical game of strategy in which two players take turns removing (or “nimming”) objects from distinct heaps or piles. On each turn, a player must remove at least one object, and may remove any number of objects provided they all come from the same heap or pile. Depending on the version being played, the goal of the game is either to avoid taking the last object or to take the last object.

Given N piles of matches. Each pile has various matches. If winner needs to take the last match, find out whether the first player could win the game or not.

Sample Input:

4
1, 3, 5, 7

Sample Output:

Lose

Given the above sample input, the first player will lose the game no matter what moves to take.

Nim Game


数据结构和算法:初级练习题 #12 – 尼姆游戏


尼姆游戏是一种两个人玩的回合制数学战略游戏游戏者轮流从一堆棋子(一共有好几堆,一次只能从其中一堆拿。)(或者任何道具)中取走一个或者多个,最后不能再取的就是输家。当指定相应数量时,一堆这样的棋子称作一个尼姆堆

给定N组火柴棍,每组火柴的数量不尽相同,如果拿到最后一根火柴的是赢家,判断先手游戏者的输赢情况。

输入样例:

4
1, 3, 5, 7

输出样例:

Lose

如上图所示的四组火柴,先手游戏者无论怎样取,最后都必输无疑。


Python Solution

Nim Game 2