# Array Circle shift algorithm?



## jfino (Jan 15, 2018)

Hi Everyone,

I came across this :
https://www.geeksforgeeks.org/array-rotation/

Allows you to shift an array in a circle 
Ex. Shift by 1 to the right.
1,2,3,4
4,1,2,3
3,4,1,2,

Can someone knowledgeable translate it to ksp? I'm sure a lot of people will find it useful! 

Would be cool to shift tables left or right.

Thanks!


----------



## EvilDragon (Jan 15, 2018)

It's pretty simple, though this is not an exact translation of the code, it's a bit leaner.


```
on init
   declare const $ARRAY_SIZE := 8
   declare $i
   declare $temp

   declare ui_table %arr[$ARRAY_SIZE] (5, 6, -100)
   declare ui_switch $Left
   declare ui_switch $Right

   { random init state... }
   $i := 0
   while ($i < $ARRAY_SIZE)
       %arr[$i] := random(-100, 100)
       inc($i)
   end while

   make_persistent(%arr)
   
   message("")
end on

on ui_control ($Left)
   $i := 0
   while ($i <= $ARRAY_SIZE - 2)
       $temp := %arr[$i]
       %arr[$i] := %arr[$i + 1]
       %arr[$i + 1] := $temp
       inc($i)
   end while

   wait(100000)
   $Left := 0
end on

on ui_control ($Right)
   $i := 0
   while ($i <= $ARRAY_SIZE - 2)
       $temp := %arr[$ARRAY_SIZE - 2 - $i]
       %arr[$ARRAY_SIZE - 2 - $i] := %arr[$ARRAY_SIZE - 1 - $i]
       %arr[$ARRAY_SIZE - 1 - $i] := $temp
       inc($i)
   end while

   wait(100000)
   $Right := 0
end on
```


----------



## jfino (Jan 15, 2018)

Oh wow that was quick!! Thanks so much! 
Works great!


----------



## TGV (Jan 16, 2018)

BTW, when you want it to run efficiently, I would not recommend that, but a round-robin queue instead: make a variable that stores the start point of the array. When you need to access the array, start at that point, and end at startingpoint - 1. Shifting the array is then as easy as incrementing the starting point.


----------



## joanhadeau (Jan 16, 2018)

This looks interesting!!

Question:
Is it possible to control the Left and Right movement with a bipolar slider? Perhaps at a set speed?
So it acts like a scrub control.


----------



## joanhadeau (Jan 16, 2018)

I did some tests and changing the switch to a slider seems to do the trick.
Now I need to make an if statement to decide if the slider is increasing or decreasing.
so I can set the "Left " and "Right " functions accordingly. 

How do you determine if a slider is increasing or decreasing?
cant seem to figure it out :'(

Thanks!


----------



## EvilDragon (Jan 16, 2018)

That can be done but in a different way. You'd use the value of the slider to choose which value from the table is read out.


----------



## joanhadeau (Jan 16, 2018)

I was thinking more graphical but then again probably use more cpu. 
So ill stick with just reading the value. 
Thanks!


----------

