Forever looping through the array

Nov 22, 2012 at 11:43pm
Hi everybody.
I'm having trouble making a leap of imagination and solving this on my own.
Here is the problem. I need to step trough the array of ints, starting anywhere in the array and in case when I reach the end of array,I want to go to the first element and continue from there. The array is only 14 ints long. So, let's say I start at position 5 and I want to make 15 steps. It will take 9 steps to arrive to the end of array and the remaining 6 steps should be made starting with position 0.
So, in a way, imagine 14 ints long array that has been bent into a circle, like a clock dial. And I'm moving along a dial in a counter clockwise direction. The starting
position every time will be different
And each time the distance I want to travel will be different. More often, less than a full circle, but some times more than a full circle.

Is something like this doable?
Nov 22, 2012 at 11:50pm
closed account (z05DSL3A)
How would you do it on paper? What data do you need to keep track of when doing it?

BTW yes it is doable, you just need to think about what you are doing.
Last edited on Nov 22, 2012 at 11:52pm
Nov 22, 2012 at 11:50pm
Yeah, it is very easy to do...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	const int SIZE = 15;
	int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

	for (int i = 0, index = rand() % SIZE; i < SIZE; i++, index++)
	{
		if (index >= SIZE)
			index -= SIZE;
		
		cout << arr[index] << endl;
	}

	return 0;
}
Nov 22, 2012 at 11:54pm

1
2
3
4
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };

for ( int i = 5; i < 20; i++ ) std::cout << a[i % 14] << ' ';
std::cout << std::endl;

Nov 22, 2012 at 11:56pm
vlad's way is better.
Nov 23, 2012 at 12:09am
(changed my mind...)
Last edited on Nov 23, 2012 at 12:20am
Nov 23, 2012 at 1:25am
Thank you every body! Modulo did the trick!
Topic archived. No new replies allowed.