# Number of ways to win chocolate game

Alice and Bob are playing a game. They have N containers each having one or more chocolates. Containers are numbered from 1 to N, where ith container has A[i] number of chocolates.

The game goes like this. First player will choose a container and take one or more chocolates from it. Then, second player will choose a non-empty container and take one or more chocolates from it. And then they alternate turns. This process will continue, until one of the players is not able to take any chocolates (because no chocolates are left).

One who is not able to take any chocolates loses the game. Note that player can choose only non-empty container.

The game between Alice and Bob has just started, and Alice has got the first Chance. She wants to know the number of ways to make a first move such that under optimal play, the first player always wins.

Example : If we have 2 containers with chocolates as follow : [2,3] then here answer is only 1

Explanation :

Only 1 set of moves helps player 1 win.

Player:      1      2      1      2      1
Chocolates: 2 3 -> 2 2 -> 1 2 -> 1 1 -> 0 1

• This is the game of Nim. Its solution is well understood. en.wikipedia.org/wiki/Nim Jul 15, 2014 at 16:16
• @HansEngler I know its game of Nim.But i need to count the ways. Jul 15, 2014 at 16:16
• could you please phrase the question clearly and precisely? Are you interested in the number of ways that the game can be played or in the number of ways in which Alice or Bob can win or in something else? Jul 15, 2014 at 16:23
• @HansEngler Number of ways to make a first move such that under optimal play, Alice always wins.If she makes first turn Jul 15, 2014 at 16:32

Hint: The solution to nim is based on the binary representation of the pile sizes (or in your case the numbers of chocolates in the various containers). If we align the various binary numbers so that place values are aligned in columns, Alice wants to leave a position for Bob where each column has an even number of $1$s in it. A move by Alice (or Bob) consists of changing some of the bits of one of the numbers with the condition that the leftmost bit change must be from $1$ to $0$ (this is because we must remove chocolates). So she has to locate the leftmost column with an odd number of $1$s (if there is no such column, Alice has no winning moves). Then Alice must make sure that her change gets that column to an even number of $1$s (and possibly other adjustments will need to be made in other further to the right columns). But in that leftmost column with an odd number of $1$s, a $1$ must change to a $0$.