Code archives/Miscellaneous/Insert value into an array

This code has been declared by its author to be Public Domain code.

Download source code

Insert value into an array by Bremer2006
This function will enable you to insert a value into an existing array. You pass the array, an index number and a value. Then the function will resize the array and insert the value into the index location.
Local a:Int[] = [0,1,2,3,4,6,7,8,9]

Print "Before: "+Len(a)+" fields"
For Local b:Int = 0 To 8
	Print a[b]
Next

a = insertIntoIntArray( a[..], 5, 5 )

Print "After: "+Len(a)+" fields"
For Local c:Int = 0 To 9
	Print a[c]
Next

Function insertIntoIntArray:Int[](Array:Int[],index:Int,value:Int)
	Local remain:Int = (Len(array)) - index
	Local result:Int[Len(array)+1]
	For Local count:Int = 0 To index-1	' copy all values before insert
		result[count] = Array[count]
	Next
	result[index] = value				' insert value
	For Local count2:Int = 0 To remain-1	' copy remaining values after insert
		result[index+count2+1] = Array[index+count2]
	Next
	Return result
End Function

Comments

None.

Code Archives Forum