开发者

how to iterate all array element starting from a random index

开发者 https://www.devze.com 2023-01-09 04:51 出处:网络
I was wondering if is it possible to iterate trough all arrays elements starting from开发者_如何学C any of its elements without pre-sorting the array.

I was wondering if is it possible to iterate trough all arrays elements starting from开发者_如何学C 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?


Use the modulus operator:

int start = 3;
for (int i = 0; i < count; i++)
{
    value = array[(start + i) % count];
}


Yes it's possible. Try this:

int index = arc4rand() % count; // picks an index 0 to 4 if count is 5
// iterate through total number of elements in array
for (int i = 0; i < count; i++)
{
    // if element 4 go back to zero
    if (index == count-1) { index = 0; }
    //do something here
    someValue = yourArray[index];
}

EDIT: When I first answered this I thought you were asking about picking the random index. I probably misunderstood. I also use the modulus operator to iterate arrays as in the first answer, and that's probably the more elegant approach. You can also use the if statement above, so I'll leave my answer here as an alternate.

0

精彩评论

暂无评论...
验证码 换一张
取 消