Flavius Josephus/ Hot Pocket simulation

504 Views Asked by At

So I was reading Problem Solving Using Data Structures Python where the author implements a queue to simulate the famous Hot Pocket/Josephus execution problem. However, I believe that this implementation is not correct since no matter how many times I tried, the last survivor, as computed by the program doesn't match up with my calculations. For instance, for the input ([0,1,2,3,4],2)), shouldn't the output be 3 instead of 1?(since it eliminates 2 first, so going by the pattern, the order of execution should be 2,4,1,0,3 making 3 the last survivor.) But the program gives an output of 1.

Here is the complete implementation:

    class Queue:
def __init__(self):
    self.items = []

def isEmpty(self):
    return self.items == []

def enqueue(self, item):
    self.items.insert(0,item)

def dequeue(self):
    return self.items.pop()

def size(self):
    return len(self.items)

def hotPotato(namelist, num):
simqueue = Queue()
for name in namelist:
    simqueue.enqueue(name)

while simqueue.size() > 1:
    for i in range(num):
        simqueue.enqueue(simqueue.dequeue())

    simqueue.dequeue()

return simqueue.dequeue()

print(hotPotato(([0,1,2,3,4],2)))

So what am I doing wrong? Any help is appreciated. Thanks in advance!

1

There are 1 best solutions below

0
On BEST ANSWER

Maybe you have some indentation problem, the output for the script below is 3 - as you suggested.

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

def hotPotato(namelist, num):
    simqueue = Queue()
    for name in namelist:
        simqueue.enqueue(name)

    while simqueue.size() > 1:
        for i in range(num):
            simqueue.enqueue(simqueue.dequeue())

        simqueue.dequeue()

    return simqueue.dequeue()
print hotPotato([0,1,2,3,4],2)