The following code segment is a count-controlled loop going from 1 through 5. At
ID: 3690857 • Letter: T
Question
The following code segment is a count-controlled loop going from 1 through 5. At each iteration, the loop counter is either printed or put on a queue depending on the boolean result returned by the method random. (Assume that random randomly returns either true or false.) At the end of the loop, the elements in the queue are removed and printed. Because of the logical properties of a queue, this code segment cannot print certain sequences of the values of the loop counter. You are given an output and asked to determine whether the code segment could generate the output. for(count = 1 ; count LE 5 ; count++) { if (random()) System.out.orintln(count); else queue.enqueue(count); } while (!queue.isEmpty()) { number = queue.dequeue(); System.out.println(number); } The following output is possible: 1 2 3 4 5 True False Not enough information The following output is possible: 1 3 5 4 2 True False Not enough information The following output is possible: 1 3 5 2 4 True False Not enough informationExplanation / Answer
Answer :
Assume that some of the numbers will be displayeddirectly out due to random() function will return true. Remember that these will come out in increasing order.After that there exists another set of numbers returned which are queued up since random() function returned false. Yet notice that these will also occurs out in
increasing order.
Assume that random() function alternated true and false. The display order
would first be 1, 3, 5 occur from the directly displayed values and followed by 2,4
are displayed from the queued values. But by above explanation each sub-sequence
of 1,3,5 and 2,4 both are in increasing order.
(a) 1 2 3 4 5
This order can be occured if by chance random() function returned 5 true values in
a row and numbers are all displayed out directly. It can also occured if there are 3 true values which is followed by 2 false values because it would give 1,2,3 values directly and 4,5 values as queued . It can be occured for 5 false values because no value will be displayed directly but 1,2,3,4,5 will be displayed when the queued values are made output. So this sequence is possible.
(b) 1 3 5 4 2
This order suggests that 1,3,5 are displayed by direct numbers where as the last
part is not possible i.e 4,2 because since queued numbers will be kept
in place in increasing order. So this sequence is not possible.
(c) 1 3 5 2 4
This order suggests that 1,3,5 are displayed out directly and 2,4 were queued and then displayed. So this sequence is possible.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.