ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer g[5][5] = {{1,1,0,0,0},
{1,0,0,1,1},
{0,0,1,0,0},
{1,0,1,1,0},
{1,0,0,0,1}}
Procedure sink(Integer i, Integer j)
if (i < 0 OR j < 0 OR i > 4 OR j > 4 OR g[i][j] == 0)
return
end if
g[i][j] = 0
sink(i + 1, j)
sink(i - 1, j)
sink(i, j + 1)
sink(i, j - 1)
End Procedure
Integer islands = 0
for (each i from 0 to 4)
for (each j from 0 to 4)
if (g[i][j] == 1)
islands = islands + 1
sink(i, j)
end if
end for
end for
Print islands- A. 4
- B. 5
- C. 6
- D. 11
Correct answer: B. 5
Each new 1 starts an island, and sink wipes out everything connected to it up, down, left or right (not diagonally). The groups are: top-left {(0,0),(0,1),(1,0)}, {(1,3),(1,4)}, {(2,2),(3,2),(3,3)}, {(3,0),(4,0)} and {(4,4)}: 5 islands.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer m[4][4], s = 0 for (each i from 0 to 3) for (each j from 0 to 3) m[i][j] = 4…
- What will be the output of the following pseudocode? Boolean comp[0..30] = all false Integer s = 0 for (each i from 2 to 30) if (not…
- What will be the output of the following pseudocode? Function isPrime(Integer n) if (n < 2) return false for (each d from 2 to n - 1) if…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function phi(Integer n)…
- What will be the output of the following pseudocode? Integer s = 0 for (each i from 1 to 99) if (i mod 2 == 1) s = s + i else s = s - i…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 100, steps = 0…