In this HackerRank Misère Nim problem solution we have Given the value of N piles of stones indexed from 0 to n – 1 and the number of stones in each pile, determine whether the person who wins the game is the first or second person to move. If the first player to move wins, print First on a new line; otherwise, print Second. Assume both players move optimally.
Problem solution in Python.
g = int(input().strip()) for _ in range(g): n = int(input().strip()) s = [int(x) for x in input().strip().split(' ')] x = 0 for i in s: x ^= i if len(set(s))==1 and 1 in s: #here x=0 or 1 if x:#odd no. of ones print("Second") else:#even no. of ones print("First") else: if x: print("First") else: print("Second")
Problem solution in Java.
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int k1 = sc.nextInt(); int l1 = 0; int max = 0; while (k1-- > 0) { int p = sc.nextInt(); l1 ^= p; max = Math.max(max, p); } System.out.println((l1 == 0 && max > 1 || l1 == 1 && max == 1) ? "Second" : "First"); } } }
Problem solution in C++.
#include <iostream> using namespace std; int main() { int T, n, s, result, count; cin >> T >> ws; for (int a0 = 0; a0 < T; a0++) { cin >> n >> ws; result = 0; count = 0; for (int i = 0; i < n; i++) { cin >> s >> ws; result ^= s; if (s <= 1) count++; } if ((count == n && result == 1) || (count < n && result == 0)) cout << "Second" << endl; else cout << "First" << endl; } return 0; }
Problem solution in C.
#include <stdio.h> #include <stdlib.h> int main(void) { int t; scanf("%d", &t); while(t--) { int n; int result = 0; scanf("%d", &n); int counter_big = 0; int counter = 0; int max = 0; for(int i = 0; i < n; i++) { int temp; scanf("%d", &temp); result ^= temp; if(temp > 0) { if(temp > 1) counter_big++; counter++; } if(temp > max) max = temp; } if(counter_big <= 1) { if(counter & 1 && max == 1) puts("Second"); else puts("First"); } else { if(result) puts("First"); else puts("Second"); } } return 0; }