I don't think the assignment is worded very carefully, particularly as there is a possible fencepost issue, but this is how I read it:
You are being asked to use modulo operations to fill an array (there is no 'queue' involved). Also, for clarity, we are going to do this
without "moving" anything.
For simplicity, let's say N=10 and M=2.
1 2 3 4 5 6 7 8 9 10
k
That is, k=3 (it is the index of the first robot after the first M robots.
Here is the fencepost problem: you are now asked to go to the "kth" position. If the robots are arranged thus (had they been moved, then the kth position is:
3 4 5 6 7 8 9 10 1 2
k
Robot 5.
Not robot 6. That said, your professor might expect you to select robot six -- you should ask for clarification. I will continue with the assumption that robot 5 is the correct choice. (And again, I've
numbered the robots starting with
one, not zero, so again, you need to ask your professor for clarification.)
As it is, the exact details don't matter, but the process does. As long as you can correctly compute the next k you are good.
So, now we have:
1 2 3 4 5 6 7 8 9 10
* k
That is, robots 3 and 5 now have a cupcake. Our next robot is going to be, according to our (possibly incorrect) assumptions above, k+k-1 == 5+5-1 == 9:
1 2 3 4 5 6 7 8 9 10
* * k
And again, 9+9-1=17. We don't have 17 robots, so we have to wrap around to the first robot. (This part was left out of your assignment's wording.)
Since there are ten robots, you can use modular arithmetic -- that is, find the remainder: 17%10 == 7. Robot 7 is the next kth robot.
1 2 3 4 5 6 7 8 9 10
* * k *
Now for the interesting part. We again update k as: k=7+7-1=13→3:
1 2 3 4 5 6 7 8 9 10
* * * *
k
Robot 3 already has a cupcake. (Chef will be so disappointed! -- Irrelevant info!) Only four of the ten robots get cupcakes.
This is essentially a sieve algorithm.
Now, the way you implement it is not too important. Using an array is a good idea. Have an array of robots, numbered by their index (as all array elements are), and the array values are simply whether or not the element (the robot) has been visited (has a cupcake).
1 2
|
bool robots[10] = { false };
...
|
Keep in mind that you don't have to have exactly as many robots as the size of your array. You can have a big array but pretend it is smaller:
1 2 3
|
bool robots[100] = { false };
int num_robots = 10;
...
|
Write a loop which only terminates if robot k has a cupcake:
1 2 3 4 5
|
k = M+1; // M <= num_robots
while (!robots[k-1])
{
k = ...
}
|
Again, the above was written with k = 1, 2, 3...
If you use the C++ convention of indexing arrays from 0, then your robots will also be indexed from 0:
1 2 3 4 5
|
k = M; // M < num_robots
while (!robots[k])
{
k = ...
}
|
When you are done, all you need to do is count the number of robots that have a cupcake.
Hope this helps.