views:

52

answers:

2

I was wondering if is it possible to iterate trough all arrays elements starting from any of its elements without pre-sorting the array.

just to be clearer suppose i have the array of 5 elements:

0 1 2 3 4

i want to read all elements starting from one of their index like:

2 3 4 0 1

or

4 0 1 2 3

the idea is to keep the element order in this way:

n ,n+1 ,..., end ,start, ..., n-1

One solution could be (pseudocode):

int startElement;
int value;
for(startElement;startElement<array.count;startElement++){
  value = array[startElement];
}
for(int n = 0; n<startElement;n++){
  value = array[n];
}

but I don't know if there's a better one. Any suggestions?

+7  A: 

Use the modulus operator:

int start = 3;
for (int i = 0; i < count; i++)
{
    value = array[(start + i) % count];
}
tzaman
I see problem with above code. This will start from 1st element in array if size of Array is 3, But we actually want to start it from 3rd element in array.
YoK
@YoK, you'll have to decide whether you're counting 0-indexed or 1-indexed. The code above actually says start at the **4th** element, since `start = 0` represents starting at the first element. And for an array of size 3, the 4th element is the first.
Tomas Lycken
A: 

Yes it's possible. You need to use a psuedorandom number picker like rand() or arc4rand() though. Something like:

int arrayElement = arc4rand() % 5; // picks a number 0 to 4
for (int i = 0; i < 5; i++)
{
    if (arrayElement > 4)
    {
        arrayElement -= 5; // after element 4 go back to zero
    }
    someValue = yourArray[arrayElement];
}
Rab
And if someone says "the modulus operator skews random results" I will send denizens of the undead to haunt their dreams.
Rab