ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (Array positions run from 1 to 10.)

What will be the output of the following pseudocode? (Array positions run from 1 to 10.)
Integer alive[1..10] = all 1, left = 10, pos = 0, count = 0
while (left > 1)
    pos = pos mod 10 + 1
    if (alive[pos] == 1)
        count = count + 1
        if (count == 3)
            alive[pos] = 0
            left = left - 1
            count = 0
        end if
    end if
end while
for (each i from 1 to 10)
    if (alive[i] == 1)
        Print i
    end if
end for
  1. A. 5
  2. B. 7
  3. C. 4
  4. D. 10

Correct answer: C. 4

This is the Josephus elimination: walking round a circle of 10 and removing every third person still present. Removal order: 3, 6, 9, 2, 7, 1, 8, 5, 10, leaving 4. (Formula check: J(1) = 0 and J(n) = (J(n − 1) + 3) mod n gives 0, 1, 1, 0, 3, 0, 3, 6, 0, 3 for n = 1…10, i.e. position 3 + 1 = 4.) 10 is the last one removed, a common confusion with the survivor.

More Pseudocode and Code Tracing questions

Exams that ask this topic