Swap array elements

Monkey Forums/Monkey Programming/Swap array elements

lom(Posted 2015) [#1]
What is the best solution to swap array elements?


Samah(Posted 2015) [#2]
Local temp:=arr[10]
arr[10] = arr[15]
arr[15] = temp



lom(Posted 2015) [#3]
Samah,
Thanks, but how can I do this with a big array? I want to swap each 5th element of an array with each 8th element.
Here's what I'm trying to do:
For Local a:Int=0 Until arr.Length Step 5
	Local temp:=arr[a]
	arr[a]=arr[a+3]
	arr[a+3]=temp
Next

But it throws an error: Array index out of range


Samah(Posted 2015) [#4]
How big is your array?


Duke87(Posted 2015) [#5]
when a reaches arr.Length
it tries to get to arr[a+3] which is out of array.

maybe check like:
For Local a:Int=0 Until arr.Length Step 5
        if a+3 < arr.Length
	    Local temp:=arr[a]
	    arr[a]=arr[a+3]
	    arr[a+3]=temp
        endif 
Next




lom(Posted 2015) [#6]
Samah,
Array length always changes.

Duke87,
Thanks for the tip, it's working now.