Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate all array element starting from a random index

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?

like image 277
Noya Avatar asked Dec 07 '22 02:12

Noya


1 Answers

Use the modulus operator:

int start = 3;
for (int i = 0; i < count; i++)
{
    value = array[(start + i) % count];
}
like image 186
tzaman Avatar answered Mar 15 '23 10:03

tzaman