logo CodeStepByStep logo

collection_mystery4

Language/Type: PHP collections Stack Queue
Author: Melissa Hovik (on 2018/01/05)

Write the result returned by the following function when passed each of the following stacks. Your answer should be in the same notation as the input collection (a comma-separated array surrounded by [] brackets). Note that a stack prints in [bottom ... top] order.

function collection_mystery4($stack) {
    $queue = [];
    $set = [];
    while (count($stack) > 0) {
        $n = array_pop($stack);
        if ($n % 2 == 0) {
            array_push($queue, $n);
        } else {
            if (!in_array($n, $set)) {
                array_push($set, $n);
            }
        }
    }
    sort($set);
    foreach ($set as $n) {
        array_push($stack, $n);
    }
    while (count($queue) > 0) {
        array_push($stack, array_shift($queue));
    }
    return $stack;
}

[1, 2, 3]
[-1, -3, -2, -3, -1]
[1, 2, 3, 4, 5]
[3, 2, 7, 3, 3, 4, 1, 1, 4]
[8, 5, 1, 2, 1, 1, 2, 1, 4, 5]

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.