I'm having trouble figuring out what's the problem in my code. The question goes like this: There's a game with a line of coins(an received array) on the board and the players can take one coin from each side. There are two players(in this case Amir & Tamar), and Amir basically has to win. The method 'win' is the strategy for Amir to win. They can both see the coins(and Tamar takes the biggest coin of each sides no matter what). The strategy I thought for Amir is to identify if there's an extremely "big" coin that no matter what the game scores, if he'll take it he will win.
public static void win(int[] arr) {
int index = findExtremeBig(arr);
int totalTamar = 0;
int totalAmir = 0;
String tamarTook = "Tamar took ";
String amirTook = "Amir took ";
for (int i = 0; i < arr.length/2; i++) {
if (index != -1) {
if ((arr.length - i - 1) == index || i + 1 == index) {
int pick = Math.min(arr[i], arr[arr.length - i - 1]);
totalAmir += pick;
System.out.println(amirTook + pick);
if (pick == arr[i]) {
arr[i] = 0;
pick = Math.max(arr[i + 1], arr[arr.length - i - 1]);
} else {
arr[arr.length - i - 1] = 0;
pick = Math.max(arr[i], arr[arr.length - i - 2]);
}
System.out.println(tamarTook + pick);
totalTamar += pick;
}
} else {
int pick = Math.max(arr[i], arr[arr.length - i - 1]);
totalAmir+=pick;
System.out.println(amirTook + pick);
if(pick == arr[i]){
arr[i] = 0;
pick = Math.max(arr[i+1], arr[arr.length - i - 1]);
} else {
arr[arr.length-i-1] = 0;
pick = Math.max(arr[i], arr[arr.length - i - 2]);
}
System.out.println(tamarTook + pick);
totalTamar += pick;
}
I think my problem is in the condition if ((arr.length - i - 1) == index || i + 1 == index)
Because if let's say the array received is: {1 ,3, 100, 2} The condition is passed and it won't recognize the 100 as the biggest number, i=0 is basically skipped. Any help? :)
Aucun commentaire:
Enregistrer un commentaire