ProgrammingModerateInfosys · Cognizant
A row of positions 1 to 20 is scanned in order. A position i is picked if no position has been picked yet, or if i minus the last picked position is at least 3. What is the number of picked positions printed?
A row of positions 1 to 20 is scanned in order. A position i is picked if no position has been picked yet, or if i minus the last picked position is at least 3. What is the number of picked positions printed?
last = none; count = 0
for i = 1 to 20
if last is none or i - last >= 3 then
count = count + 1; last = i
end if
end for
Print count- A. 10
- B. 5
- C. 7
- D. 20
Correct answer: C. 7
Picks happen at 1, 4, 7, 10, 13, 16 and 19, which is 7 positions. A gap of two allows 10 picks, a strict gap of four gives 5 picks, and counting every position ignores the rule.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below…
- Tasks with the same letter must be separated by at least n = 2 idle or other slots. The task string is AAABBC. The greedy formula below…
- Items of sizes 5, 7, 5, 2, 4, 2, 5, 1, 6 are packed in this order into bins of capacity 10 using the first-fit rule: put each item into…
- Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending…
- Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals…
- Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at…