In this HackerRank Zero-Move Nim problem solution John and Kate modified Nim by adding the following rule, which they call a Zero-Move:
For each non-empty pile, either player can remove 0 items from that pile and have it count as their move; however, this move can only be performed once per pile by either player. For example, let’s say pile I initially have Pi = 2 items in it. If John decides to use a Zero-Move on pile i, then neither John nor Kate can perform another Zero-Move on the pile i; that said, either player is free to perform a Zero-Move on any other non-empty pile that hasn’t had a Zero-Move performed on it yet.
John and Kate play g games of Zero-Move Nim. Given the number of items in each pile for each game, determine whether or not John can win the game if he always moves first and each player always moves optimally (i.e., never makes a move that causes them to lose if some better, winning move exists). For each game, print W on a new line if John can win; otherwise, print L instead.
Problem solution in Python.
test_case = int(input()) for temp_test_case in range(test_case): n = int(input()) s = input() a = [int(elem) for elem in s.split() ] # print (a) x = 0 for i in a: if i == 0: continue if i % 2 == 0: x = x ^ (i-1) else: x = x ^ ( i + 1) # print(x) if x != 0: print('W') else: print('L')
Problem solution in Java.
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int g = in.nextInt(); for(int a0 = 0; a0 < g; a0++){ int n = in.nextInt(); int[] p = new int[n]; for(int p_i=0; p_i < n; p_i++){ p[p_i] = in.nextInt(); } int nimsum = 0; for (int i : p){ if (i == 0) continue; if ((i & 1) == 0) nimsum ^= i - 1; else nimsum ^= i + 1; } System.out.println(nimsum == 0 ? "L" : "W"); } } }
Problem solution in C++.
#include <iostream> #include <algorithm> #include <vector> #include <limits.h> #include <math.h> using namespace std; #define rep(i, n) for ((i) = 0; (i) < (n); (i)++) #define ran(i, m, n) for ((i) = (m); (i) < (n); (i)++) int main(int argc, char *argv[]) { int g, n, i, a; cin >> g; while (g--) { cin >> n; a = 0; while (n--) { cin >> i; a ^= i&1 ? i+1 : i-1; } if (a) puts("W"); else puts("L"); } return 0; }
Problem solution in C.
#include <stdio.h> #include <stdlib.h> int main(){ int g,n,x,s; scanf("%d",&g); while(g--){ scanf("%d",&n); s=0; while(n--){ scanf("%d",&x); if(x%2) s^=x+1; else s^=x-1; } if(s) printf("Wn"); else printf("Ln"); } return 0; }