سوال ۶۲ کنکور ارشد علوم کامپیوتر ۱۴۰۵
آرایه شامل عدد صحیح در مکان و است. لازم است عناصر آرایه بهصورت چرخهای بهاندازه مکان به سمت چپ منتقل شوند، که در آن است. یک الگوریتم ناقص برای انجام این کار در زمان خطی، بدون استفاده از آرایه دیگر در زیر آورده شده است. الگوریتم را با پر کردن جاهای خالی کامل کنید. (فرض کنید متغیرها بهطور مناسب تعریف شدهاند.)
min = n; i = 0;
while (...){
temp = A[i]; j = i;
while (...){
A[j] = ...
j = (j + k) mod n;
If (j < min) then
min = j;
}
A[(n + i - k) mod n] = ...
i = ...
}
پاسخ صحیح: گزینهٔ A — ; ; ; ;
This is the classic in-place cyclic-replacement (“juggling”) algorithm for a left rotation.
What a left rotation must do. Shifting the array places to the left sends the element at index to index ; that is, the new value of is the old .
Third blank — the inner move. Following one cycle we repeatedly pull the next element back: The index must be reduced modulo , so the blank is . Options 2–4 write (or ) with no , which reads past the end of the array — eliminated.
Second blank — the inner stop test. We saved . The cycle ends at the slot that must receive , namely index (the predecessor of in the cycle). Executing the body there would write , but was already overwritten. Hence loop while , then fill that slot with (fourth blank). Since , options 2 and 3 (j != (n+i) mod n) would never enter the inner loop — eliminated.
First blank — the outer stop test. The permutation splits into cycles, with representatives . The variable (started at ) records the smallest index actually stepped onto. The cycle through is exactly the multiples of , so its smallest nonzero member is ; after the first cycle , and later cycles only reach indices . Thus the outer loop should run while (i.e. ). i > min (options 2, 4) is backwards — eliminated. The outer loop advances with .
Quick trace ().
- : , , stop at , set ; now .
- : , , set .
- is not → stop. All six elements are rotated in time, in place.
Every blank matches option 1.
Exam trick: In cycle-following rotation remember two things — every index is taken , and the number of independent cycles is . Here is just a clever way to discover on the fly.