Waiter

  • + 0 comments

    I guess that this task is designed to help us prepare for the real challenges of engineering work, as it is a great exercise in dealing with confusing customer requirements ;)

    What helped me understand the baffling description and solve the problem was following the proposed analogy with plates, and visualizing how they are being transferred from/to different stacks by the waiter (I even drew a couple of diagrams on a sheet of paper).

    JavaScript solution:

    function waiter(number, q) {
        // Write your code here
        const answers = [];
    
        const primes = [];
        let num = 2;
        while (primes.length < q) {
            let isPrime = true;
            for (let div = 2; num > div; div++) {
                if (num % div === 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) primes.push(num);
            num++;
        }
        
        function movePlatesOneByOne (fromStack, toStack) {
            for (let i = fromStack.length - 1; i >= 0; i--) {  
                toStack.push(fromStack[i]);
            }
            fromStack.length = 0;
        }
    
        const plates = number.reverse();
        const stackA = []; // divisible by prime: false
        const stackB = []; // divisible by prime: true
    
        for (let prime of primes) {
            if (stackA.length) {
                movePlatesOneByOne(stackA, plates);
            }
            
            for (let plate of plates) {
                if (plate % prime === 0) {
                    stackB.push(plate);
                } else {
                    stackA.push(plate);
                }
            }
            plates.length = 0;
            
            if (stackB.length) {
                movePlatesOneByOne(stackB, answers);
            }
        }
        
        if (stackA.length) {
            movePlatesOneByOne(stackA, answers);
        }
        
        return answers;
    }
    
    
    

    `