TheCDC

Untitled

Mar 11th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. # https://www.reddit.com/r/computerscience/comments/azbnoh/coding_interview_problem/
  2.  
  3. """
  4. There are 'n' people in a circle. Each person has an even number of rocks. At each 'tick', they simultaneously pass half their pile of rocks to the person to their left. After the tick, for any person that has an odd number of rocks, they will receive one additional rock to even out their new pile (so as to avoid fractions of rock to pass around).
  5.  
  6. Note: The additional rock given to odd piles do not come from any of the people in the circle. It just appears on their pile.
  7.  
  8. How many ticks does it take till all people have an equal number of rocks in their pile? (if the number of moves is more than 100, than we assume it is "impossible").
  9.  
  10. Example (this a list of people's stack of rocks at the beginning of simulation, going in clock-wise order):
  11.  
  12. 8 32 10 2 48 34 (17 ticks)
  13.  
  14. 1000 100 10 2 (19 ticks)
  15.  
  16. I can't seem to think of a way to optimize this, or any way of solving this without just simulating the process (which is a very inefficient way of finding the answer).
  17. """
  18. from math import ceil
  19. import random
  20.  
  21.  
  22. def tick(l):
  23.     """Return the next state of the simulation"""
  24.     buffer = l[:]
  25.     for index, item in enumerate(l):
  26.         buffer[index] = ceil(item/2) + ceil(l[index-1]/2)
  27.     return buffer
  28.  
  29.  
  30. def check(l):
  31.     """Check whether a simulation state is terminal."""
  32.     return len(set(l)) == 1
  33.  
  34.  
  35. def simulate(l):
  36.     """Step through states until a terminal state is reached."""
  37.     c = 0
  38.     while True:
  39.         yield c, l
  40.         if check(l):
  41.             break
  42.         l = tick(l)
  43.         c += 1
  44.  
  45.  
  46. l = [random.randint(1, 100) for i in range(random.randint(3, 20))]
  47. for state in simulate(l):
  48.     print(*state, sep='\t')
Add Comment
Please, Sign In to add comment