Thursday, 29 December 2016

Samu and Vibhu

‘samu’ and ‘vibhu’ are playing a game where there are N integers from 1 to N lying on the table.
In each turn, the player gets to pick one integer to mark as visited from among the previously unvisited ones.
If in a turn, the player picks a number which completes the picking of three consecutive numbers, he wins.
i.e., say at some stage in the game 2 and 4 are already picked(visited) if the player now picks 3, he wins.
Assuming samu starts first and both the players play perfectly optimally, who is the winner.

public class Samu_Vibhu {
private List _inputs = new ArrayList<>();
private Random _random = new Random();
private List _samuPicks;
private List _vibhuPicks;
public Samu_Vibhu(int[] inputs) {
for (int index = 0; index < inputs.length; index++) {
this._inputs.add(inputs[index]);
}
this._samuPicks = new ArrayList<>();
this._vibhuPicks = new ArrayList<>();
}
private int pickOne() {
return this._inputs.remove(this._random.nextInt(this._inputs.size()));
}
private boolean anyOneWon(List inputs, int input) {
return inputs.contains(input -1) && inputs.contains(input + 1);
}
public void play() {
boolean samuTurn = true;
boolean won = false;
int pick;
while(this._inputs.size() > 0 && !won) {
pick = this.pickOne();
System.out.println((samuTurn ? "Samu" : "Vibhu") + " picked " + pick);
if(samuTurn) this._samuPicks.add(pick);
else this._vibhuPicks.add(pick);
won = this.anyOneWon((samuTurn ? this._samuPicks : this._vibhuPicks), pick);
if(!won) samuTurn = !samuTurn;
}
if(won && samuTurn) System.out.println("Samu won");
else if(won) System.out.println("Vibhu won");
else System.out.println("Draw");
}

}

static void demoSamuVibhu() {
      int[] testCase = new int[] {1, 4, 5, 7, 8, 10, 34, 56, 67, 78, 3, 9, 57, 58 };
      Samu_Vibhu samuVibhu = new Samu_Vibhu(testCase);
      samuVibhu.play();
}

No comments: