In this HackerRank Introduction to Nim Game problem solution we have Given the value of N and the number of stones in each pile, determine the game's winner if both players play optimally.

HackerRank Introduction to Nim Game problem solution


Problem solution in Python.

from functools import reduce

for _ in range(int(input())):
    n = int(input())
    piles = list(map(int, input().split()))
    if reduce(lambda x, y: x ^ y, piles) == 0:
        print('Second')
    else:
        print('First')


Problem solution in Java.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        while (t > 0) {
            --t;
            int n = scanner.nextInt();
            int x = 0;
            for (int i = 0; i < n; ++i) {
                x ^= scanner.nextInt();
            }
            
            System.out.println(x > 0 ? "First" : "Second");
        }
    }
}


Problem solution in C++.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int T, N, s;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
  cin >> T;
  for (int t = 0; t < T; t++) {
    cin >> N;
    int tot = 0;
    for (int i = 0; i < N; i++) {
      cin >> s;
      tot ^= s;
    }
    if (tot == 0)
      cout << "Second" << endl;
    else
      cout << "First" << endl;
  }
  return 0;
}


Problem solution in C.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int g;
    scanf("%d", &g);
    for (int x = 0; x < g; x++){
        int n, sum = 0;
        scanf("%d", &n);
        int s;
        for (int y = 0; y < n; y++){
            scanf("%d", &s);
            sum = sum ^ s;
        }
        if (sum == 0){
            printf("Second\n");
        }
        else {
            printf("First\n");
        }
    }
    return 0;
}