In this Gaming Array 1 HackerRank solution, Andy wants to play a game with his little brother, Bob. The game starts with an array of distinct integers and the rules are as follows:
- Bob always plays first.
- In a single move, a player chooses the maximum element in the array. He removes it and all elements to its right. For example, if the starting array , then it becomes after removing .
- The two players alternate turns.
- The last player who can make a move wins.
Andy and Bob play 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
.
To continue the example above, in the next move Andy will remove . Bob will then remove and win because there are no more integers to remove.
Function Description
Complete the gamingArray function in the editor below.
gamingArray has the following parameter(s):
- int arr[n]: an array of integers
Returns
– string: either ANDY
or BOB
Input Format
The first line contains a single integer , the number of games.
Each of the next pairs of lines is as follows:
- The first line contains a single integer, , the number of elements in .
- The second line contains distinct space-separated integers where .
Constraints
- Array contains distinct integers.
For of the maximum score:
- The sum of over all games does not exceed .
For of the maximum score:
- The sum of over all games does not exceed .
Gaming Array 1 HackerRank Solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C#
public static string gamingArray(List<int> arr)
{
List<Tuple<int,int>> sortedArr = new List<Tuple<int,int>>();
for (int i = 0; i < arr.Count; i++)
{
sortedArr.Add(new Tuple<int, int>(i, arr[i]));
}
sortedArr.Sort((a, b) => b.Item2-a.Item2);
bool bobWins = false;
int last = int.MaxValue;
foreach (var item in sortedArr)
{
var current = item.Item1;
if (current<last)
{
last = current;
bobWins = !bobWins;
}
if (last == 0)
{
break;
}
}
return bobWins ? "BOB" : "ANDY";
}
Problem Solution in Python
def gamingArray(arr):
maxi=-1
max_count = 0
for i in arr:
if i>maxi:
maxi=i
max_count+=1
if max_count%2!=0:
return "BOB"
return "ANDY"
Problem Solution in JavaScript
function gamingArray(arr) {
var turn = -1;
var len = arr.length;
var limit = 0;
while(len>0){
var max = arr[0];
limit = 0;
for(var i=0;i<len;i++){
if(arr[i]>max){
max = arr[i];
limit = i;
}
}
len = limit;
turn++;
}
if(turn%2==0){
return "BOB";
}else{
return "ANDY";
}
}
Leave a Reply