ProgrammingVery hardTCS NQT · Accenture
The procedure below counts the cyclic rotations of "abab" that are equal to "abab" itself, checking the rotations obtained by moving k characters from the front to the back for k = 0 to n - 1. What is printed?
The procedure below counts the cyclic rotations of "abab" that are equal to "abab" itself, checking the rotations obtained by moving k characters from the front to the back for k = 0 to n - 1. What is printed?
count = 0
for k = 0 to n - 1
rotation = s[k..n-1] + s[0..k-1]
if rotation == s then count = count + 1
end for
Print count- A. 2
- B. 1
- C. 4
- D. 0
Correct answer: A. 2
The rotations are abab, baba, abab and baba for k = 0 to 3, so two of them equal the original. Leaving out the identity rotation gives 1, printing the length gives 4, and counting rotations equal to abba gives 0.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are…
- Ropes of lengths 1, 2, 3, 4 and 5 are merged two at a time with cost equal to the sum of the two lengths. The greedy merges the two…
- A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy…
- The greedy below repeatedly increases the smallest element of the array [3, 1, 2] by 1, three times in total. What is the minimum value of…
- For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder…
- The Fibonacci numbers F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) satisfy gcd(F(m), F(n)) = F(gcd(m, n)). The procedure below uses this…