Skip to content

Commit 2e89f90

Browse files
committed
Added hard/nim_winner
1 parent cda7d23 commit 2e89f90

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

hard/nim_winner.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Using the JavaScript language, have the function NimWinner(arr) take the
3+
* array of integers stored in arr which will represent the amount of coins in
4+
* each pile. For example: [2, 4, 1, 3] means there are 4 piles of coins and
5+
* there are 2 coins in the first pile, 4 in the second pile, etc. Nim is played
6+
* by each player removing any number of coins from only one pile, and the
7+
* winner is the player who picks up the last coin. For example: if arr is [1,
8+
* 2, 3] then for example player 1 can remove 2 coins from the last pile which
9+
* results in [1, 2, 1]. Then player 2 can remove 1 coin from the first pile
10+
* which results in [0, 2, 1], etc. The player that has the last possible move
11+
* taking the last coin(s) from a pile wins the game. Your program should output
12+
* either 1 or 2 which represents which player has a guaranteed win with perfect
13+
* play for the Nim game.
14+
*
15+
* https://www.coderbyte.com/results/bhanson:Nim%20Winner:JavaScript
16+
*
17+
* @param {array} arr
18+
* @return {number}
19+
*/
20+
function nimWinner(arr) {
21+
// https://en.wikipedia.org/wiki/Nim#Mathematical_theory
22+
const nimSum = arr.reduce((nimSum, num) => nimSum ^ num);
23+
const winningPlayer = nimSum === 0 ? 2 : 1;
24+
return winningPlayer;
25+
}
26+
27+
module.exports = nimWinner;

hard/nim_winner.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const nimWinner = require('./nim_winner');
2+
3+
describe('nimWinner()', () => {
4+
test('passes Coderbyte.com tests', () => {
5+
expect(nimWinner([1, 2, 3])).toBe(2);
6+
7+
expect(nimWinner([1, 1, 1, 4, 5, 4])).toBe(1);
8+
9+
expect(nimWinner([1, 1, 1, 1])).toBe(2);
10+
11+
expect(nimWinner([1, 1, 1])).toBe(1);
12+
13+
expect(nimWinner([1, 2, 3, 4])).toBe(1);
14+
15+
expect(nimWinner([1, 2, 3, 4, 5, 6])).toBe(1);
16+
17+
expect(nimWinner([1, 2, 3, 4, 5, 6, 7])).toBe(2);
18+
19+
expect(nimWinner([3, 3, 3, 3])).toBe(2);
20+
21+
expect(nimWinner([5, 1, 2, 4, 2])).toBe(2);
22+
23+
expect(nimWinner([5, 5, 1, 4, 4])).toBe(1);
24+
});
25+
});

0 commit comments

Comments
 (0)