Waiter

  • + 0 comments

    As usual, when you see the completion percentage for a question go below 90% you can suspect that it's going to be a bit nasty...

    This problem has two parts: generating the first 'q' primes, and then doing the plate sorting/stacking.

    Python 3:

    def eratosthenes():
        from collections import defaultdict
        composites = defaultdict(list)
        x = 2
        while True:
            if x in composites:
                for c in composites[x]:
                    composites[c+x].append(c)
                del composites[x]
            else:
                yield x
                composites[x*x] = [x]
            x += 1
    
    def waiter(number, q):
        plates = number
        answers = []
        primes = eratosthenes()
        for _ in range(q):
            A = []
            B = []
            prime = next(primes)
            while plates:
                plate = plates.pop()
                if plate % prime == 0:
                    B.append(plate)
                else:
                    A.append(plate)
            answers.extend(reversed(B))
            plates = A
        answers.extend(reversed(A))
        return answers