Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/main/java/com/thealgorithms/maths/NimGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.thealgorithms.maths;

/**
* Nim Game: Two players take turns removing 1 to 3 stones from a pile.
* The player who removes the last stone wins. Returns true if the first
* player can guarantee a win given n stones.
*
* <p>Key insight: if n is a multiple of 4, the second player always wins
* because whatever the first player takes (1-3), the second player can
* always take enough to leave another multiple of 4.
*
* <p>Time complexity: O(1), Space complexity: O(1)
*
* @see <a href="https://leetcode.com/problems/nim-game/">LeetCode #292</a>
*/
public final class NimGame {
private NimGame() {
}

public static boolean canWinNim(int n) {
return n % 4 != 0;
}
}
24 changes: 24 additions & 0 deletions src/test/java/com/thealgorithms/maths/NimGameTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.thealgorithms.maths;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class NimGameTest {

@Test
public void testFirstPlayerWins() {
assertTrue(NimGame.canWinNim(1));
assertTrue(NimGame.canWinNim(2));
assertTrue(NimGame.canWinNim(3));
assertTrue(NimGame.canWinNim(5));
}

@Test
public void testSecondPlayerWins() {
assertFalse(NimGame.canWinNim(4));
assertFalse(NimGame.canWinNim(8));
assertFalse(NimGame.canWinNim(12));
}
}
Loading