Program to find winner of a rower breaking game in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array height. There are n different towers with different height. Amal and Bimal are playing a game. The game rules are like below

  • Amal always plays first

  • During each move, the current player selects a tower of height X and break it down into Y different towers of height Z each. [Y*Z = X; X and Y > 1]

  • Whoever has no move will lose the game

We have to find the winner's name.

So, if the input is like height = [3,1,2], then the output will be Bimal, because the initial heights are {3,1,2}. If Amal breaks the height of tower 2 to two towers of height 1, then new height array will be {3,1,1,1}, Bimal can break tower with height 3 and make three towers of height 1, so Amal has no move hence Bimal wins.

To solve this, we will follow these steps −

  • Define a function util() . This will take limit, initial limit value is 10^3+5
  • result := an array of size limit and fill with 0
  • for i in range 2 to limit - 1, do
    • s := a new set
    • for j in range 1 to floor of square root of i, do
      • d := quotient of i/j, r := remainder of i/j
      • if r is same as 0, then
        • if j is odd, then
          • insert result[d]) into s
        • if d is odd, then
          • insert result[j] into s
    • j := 0
    • while j is present in s, do
      • j := j + 1
      • result[i] := j
  • return result
  • g := util()
  • From the main method, do the following −
  • r := 0
  • for each i in height, do
    • r := r XOR g[i]
  • if r is non-zero, then
    • return "Amal"
  • otherwise,
    • return "Bimal"

Example

Let us see the following implementation to get better understanding −

def util(limit=10**3+5):
   result = [0] * limit

   for i in range(2, limit):
      s = set()
      for j in range(1, int(i**0.5)+1):
         d, r = divmod(i, j)

         if r == 0:
            if j & 1:
               s.add(result[d])
            if d & 1:
               s.add(result[j])

      j = 0
      while j in s: j += 1
      result[i] = j

   return result

g = util()

def solve(height):
   r = 0

   for i in height:
      r ^= g[i]

   if r:
      return "Amal"
   else:
      return "Bimal"

height = [3,1,2]
print(solve(height))

Input

[3,1,2]

Output

Bimal
raja
Updated on 23-Oct-2021 07:44:55

Advertisements