swap places in a circle game

105 Views Asked by At

Here's the game: imagine A people sitting around the table. The game has B rounds. In the i-th round, the person sitting on the square gets up and says: "It's my turn". then he changes his place with the person on the right as the i-th number of prime numbers = [2,3,5,..]. find the sits of people after B round.
example:
we have A=5 people and B=3 rounds.
first round: enter image description here

second round: enter image description here

third round: enter image description here

here is the code I write:

players = list(range(1,a+1))

for i in range(b):
    player = players[0]
    if(primes[i]<len(players)):
        players.pop(0)
        players.insert(primes[i],player)
    elif (primes[i]>=len(players)) :
        pos = primes[i] % (len(players))
        round = int(primes[i] / (len(players)))
        players.pop(0)
        for j in range(round):
            x=players[0]
            players.pop(0)
            players.append(x)
        players.insert(pos,player)

It works, however, I believe that there is a more efficient algorithm to find the numbers placed in the last round because it gets too slow if b was a huge number. Any help would be appreciated.

1

There are 1 best solutions below

0
EliteGamerSiddhu On

You are popping and inserting values in the list which leads to the program to create new instances of the popped list and then return it. For a better code i have just replaced the values in the memory of the lists which keeps the entire list intact throughout the run and saves a lot of time.

primes = <Insert your list of primes>

def getInIndex(n, round):  #To keep values in the list index
    while round > n - 1:
        round -= n
    return round

n = int(input('Enter number of players: ')) #Get number of players
rounds = int(input('Enter number of rounds: ')) #Get number of rounds
players = [i for i in range(1,n+1)] #Create the player list starting from 1

for i in range(rounds):
    prime = primes[i]
    for round in range(prime):
        x = getInIndex(n, round)
        y = getInIndex(n, round + 1)

        temp = players[y]
        players[y] = players[x]
        players[x] = temp

print(players)