View Single Post
Peace-Maker
SourceMod Plugin Approver
Join Date: Aug 2008
Location: Germany
Old 09-14-2016 , 02:12   Re: Rotating an Array?
Reply With Quote #10

Depending on the size of the array, you might want to consider something like this to avoid mutation of the array at all.

PHP Code:
native void printnum(int n);
native void print(const char[] str);

public 
void main()
{
  
int arrayNums[] = { 123};
  
int arrayStart 0;
  
  
#define CircleIndex(%1) arrayNums[(arrayStart + %1) % sizeof(arrayNums)]
  #define ShiftArray(%1) arrayStart = (arrayStart + %1) % sizeof(arrayNums)
  
  
print("Starting with\n");
  for(
int i=0i<sizeof(arrayNums); i++)
    
printnum(CircleIndex(i));
  
  for (
int x=0x<5x++)
  {
    print(
"After shifting\n");
    
ShiftArray(1);
    for(
int i=0i<sizeof(arrayNums); i++)
      
printnum(CircleIndex(i));
  }

Your array doesn't start at index 0 anymore, but at index arrayNumsStart. You wrap the (arrayNumsStart + i) index around when reaching the array size to start at the beginning again.

Quote:
Originally Posted by Output
Starting with
1
2
3
After shifting
2
3
1
After shifting
3
1
2
After shifting
1
2
3
After shifting
2
3
1
After shifting
3
1
2
Edit: Use this to allow negative shifting as well.
PHP Code:
#define ShiftArray(%1) arrayStart = (arrayStart + %1 + sizeof(arrayNums)) % sizeof(arrayNums) 
__________________

Last edited by Peace-Maker; 09-14-2016 at 02:16. Reason: Consider ShiftArray(-1) as well
Peace-Maker is offline