Showing posts with label algorithm. Show all posts
Showing posts with label algorithm. Show all posts

Tuesday, November 18, 2014

Numbers Game Challenge

An interesting programming challenge of Numbers Game proposed by the DevDraft aroused my attention. Though this semester is rough, I still spent some time taking the challenge and achieved 100% code correctness by passing all the big integer test cases up to 10^10. According to their editorial, my approach falls into the bottom up category which is more efficient at runtime than recursive solutions.

Problem Statement

A turn-based two-player game is played as follows. There are three positive integers, which are given initial values at the beginning of the game. The two players alternate turns. Each player must, on their turn, choose exactly one of the integers and replace it with the average of the other two, rounded down to the nearest integer if the average is not an integer. For example, if the integers currently in play are 4, 9, and 12, the player whose turn it is may choose one of the following three actions:
  1. Replace 4 with (9 + 12) / 2 = 10 (rounded down), changing to {9, 10, 12}. 
  2. Replace 9 with (4 + 12) / 2 = 8, changing the set of integers to {4, 8, 12}.
  3. Replace 12 with (4 + 9) / 2 = 6 (rounded down), changing to {4, 6, 9}. 
No player, however, is allowed to make a move that would not change which integers are present. In our example, suppose the first player chooses to replace 9 with 8 according to the second option above. It would now be the second player's turn to act on the integers {4, 8, 12}. The second player would not be allowed to choose to replace 8, because the replacement for 8 would be (4 + 12) / 2 = 8, which would lead to no change in the integers present. The second player therefore has only two options:
  1. Replace 4 by (8 + 12) / 2 = 10, passing {8, 10, 12} back to the first player.
  2. Replace 12 by (4 + 8) / 2 = 6, passing {4, 6, 8} back to the first player.
A player loses if there are no valid moves available on their turn. For example, if the set of integers on a player's turn is {3, 3, 3}, there is no available move that does not violate the constraint that a player must make a change to the integers present, since no matter which of the 3s is chosen, the replacement would be (3 + 3) / 2 = 3. Having no valid moves is the only way in which a player can lose; the opposing player then wins.

You are playing the above game against an AI. Unfortunately for you, it is a supercomputer that has already predicted all possible games on all possible inputs and knows all the optimal strategies to use against you. Your only hope is that you're allowed to choose whether you'd like to take the first turn, or let the computer play first. Can you find a way to always win the game?