Header Ad

HackerRank Chocolate in Box problem solution

In this HackerRank Chocolate in Box problem solution Dexter and Debra are playing a game. They have N containers each having one or more chocolates. Containers are numbered from 1 to N, where the ith container has A[i] number of chocolates.

The game goes like this. The first player will choose a container and take one or more chocolates from it. Then, the second player will choose a non-empty container and take one or more chocolates from it. And then they alternate turns. This process will continue until one of the players is not able to take any chocolates (because no chocolates are left). One who is not able to take any chocolates loses the game. Note that players can choose only non-empty containers.

The game between Dexter and Debra has just started, and Dexter has got the first Chance. He wants to know the number of ways to make a first move such that under optimal play, the first player always wins.

HackerRank Chocolate in Box problem solution


Problem solution in Python.

n=int(input())
a=[int(x) for x in input().split(' ')]
xa=0
for x in a:
  xa^=x
turns=sum(1 for x in a if x^xa<x)
print(turns)


Problem solution in Java.

import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = in.nextInt();
		}
		
		int nimSum = 0;
		for (int i = 0; i < n; i++) {
			nimSum = nimSum ^ a[i];
		}
		
		if (nimSum == 0) {
			System.out.println(0);
		} else {
			int count = 0;
			for (int i = 0; i < n; i++) {
				if ((nimSum ^ a[i]) < a[i]) {
					count++;
				}
			}
			
			System.out.println(count);
		}	
	}
}


Problem solution in C++.

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <queue>
using namespace std;
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
int main()
{
	int n;
	cin>>n;
	int x;
	vector <int> pos(31,0);
	for (int i = 0; i < n; ++i)
	{
		cin>>x;
		for (int j = 0; j < 31; ++j)
		{
			if(x%2==1)
				pos[j]++;
			x/=2;
		}
	}
	for (int i = 30; i >= 0; --i)
	{
		if(pos[i]%2)
		{
			cout<<pos[i]<<"\n";
			return 0;
		}
	}
	cout<<"0\n";
	return 0;
}


Problem solution in C.

#include <stdio.h>

int main()
{
    int n;
    int cnt=0;
    int arr[1000000];
    int allxor = 0;
    scanf("%d",&n);
    for (int i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
        allxor ^= arr[i];
    }
    for (int i=0;i<n;i++)
        if (arr[i] > (allxor^arr[i]))
            cnt++;
    printf("%d\n",cnt);
    
}


Post a Comment

0 Comments