Advertisement
bokoness

אמיר ותמר

Jun 23rd, 2020
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. /**
  2.      * A game with two players, each can pick a number from the sides of the array
  3.      * The winner is the one who finished with the highest sum
  4.      * the method ensures that the first player (Amir) will never loose
  5.      *
  6.      * @param k the game board
  7.      *          Time complexity - O(n) - because the loop iterates the array only once
  8.      */
  9.     public static void win(int[] k) {
  10.         //finding the highest score path between the odd indexes and the even indexes
  11.         int countOdd = 0;
  12.         int countEven = 0;
  13.         boolean amirTookOddPath;
  14.         for (int i = 0; i < k.length; i++) {
  15.             if (i % 2 == 0)
  16.                 countEven += k[i];
  17.             else
  18.                 countOdd += k[i];
  19.         }
  20.         amirTookOddPath = countOdd >= countEven ? true : false;
  21.  
  22.         int min = 0, max = k.length - 1;
  23.         //the odd path is the winning path
  24.         while (min < max) {
  25.             //Amir's path - the highest count of values between the odd indexes and the even indexes
  26.             if (amirTookOddPath ? min % 2 != 0 : min % 2 == 0) {
  27.                 System.out.println("Amir took " + k[min]);
  28.                 min++;
  29.             } else {
  30.                 System.out.println("Amir took " + k[max]);
  31.                 max--;
  32.             }
  33.             //Tamar's path - the opposite path of Amir, always choosing the highest value between the two
  34.             if (k[max] > k[min]) {
  35.                 System.out.println("Tamar took " + k[max]);
  36.                 max--;
  37.             } else {
  38.                 System.out.println("Tamar took " + k[min]);
  39.                 min++;
  40.             }
  41.         }
  42.         System.out.println("Final score:");
  43.         System.out.println("Amir total " + (amirTookOddPath? countOdd : countEven));
  44.         System.out.println("Tamar total " + (amirTookOddPath? countEven : countOdd));
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement