In this HackerRank Gaming Array problem solution, Andy and Bob play G games. Given the initial array for each game, find and print the name of the winner on a new line. If Andy wins, print ANDY; if Bob wins, print BOB.
Problem solution in Python.
#!/bin/python3 import sys g = int(input().strip()) for a0 in range(g): n = int(input().strip()) game = map(int, input().strip().split()) if n==0: print("ANDY") continue elif n==1: print("BOB") continue maxes = [] cur_max = -float("inf") for i, num in enumerate(game): if num > cur_max: cur_max = num maxes.append(i) if len(maxes) % 2 == 0: print("ANDY") else: print("BOB")
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(); while (g > 0) { int l = in.nextInt(); int[] arr = new int[l]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int i = 0; i < l; i++) { arr[i] = in.nextInt(); int inv = arr[i] * -1; pq.add(inv); map.put(arr[i], i); } int turn = 1; int cur = arr.length - 1; while (true) { while (true) { int max = pq.poll() * -1; int index = map.get(max); if (index <= cur) { cur = index; break; } } if (cur == 0) break; if (turn == 0) turn = 1; else turn = 0; } if (turn == 0) System.out.println("ANDY"); else System.out.println("BOB"); g--; } } }
Problem solution in C++.
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; typedef long long ll; int main(){ ll g; cin >>g; vector<ll> winners (g); for (ll gi=0;gi<g;gi++){ ll n; cin >>n; vector<ll> A (n); for (ll i=0;i<n;i++){ cin >> A[i]; } ll records=0; ll crec=0; for (ll i=0;i<n;i++){ if (A[i]>crec){ records++; crec=A[i]; } } if (records%2==0){ winners[gi]=1; } else{ winners[gi]=2; } } for (ll gi=0;gi<g;gi++){ if (winners[gi]==1){ cout << "ANDY" <<endl; } if (winners[gi]==2){ cout << "BOB" <<endl; } } return(0); }
Problem solution in C.
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main(){ int g,i,j,k,l; scanf("%d",&g); for(int a0 = 0; a0 < g; a0++){ long int n; scanf("%ld",&n); long long int *a=malloc(sizeof(long long int)*n); long long int max=0; long long int c=1; for(i=0;i<n;i++) { scanf("%lld",&a[i]); } max=a[0]; for(i=0;i<n;i++) { if(a[i]>max) { max=a[i]; c++;} } if(c%2==0) printf("ANDYn"); else printf("BOBn"); } return 0; }