User:Sclerocephalus

From Creation Kit
Jump to: navigation, search

A short function for sorting arrays

The following function makes use of the so-called 'bubble sort' procedure, which works as follows:

Compare the float on the first position of an array ( float(1) ) with the float on the second position ( float(2) ) and swap them if float(1) > float(2). Then repeat this with float(2) / float(3), float(3) / float(4) and so on to float(n-1) / float(n), i.e. until the end of the array is reached. When this is done, only one float in the array is on its final position: the last one.

To get the second last position right, the whole procedure has to be repeated, but stopping now one element short of the end of the array, i.e. the last comparison in the second loop will be float(n-2) / float(n-1). The next loop will stop at float(n-3) / float(n-2), and so on until there only remains float(0) / float(1) in the last loop. Then, the job is done.

To implement this in Papyrus, we need two loops: an inner loop (Index1) that scans the array, starting from position 0 and finishing at Index2-1, and an outer loop that counts Index2 down from n to 1 (where n is the last position of the array):


Function SortArray (Float[] MyArray)
 
Int Index1
Int Index2 = MyArray.Length - 1
 
	While (Index2 > 0)
		Index1 = 0
		While (Index1 < Index2)
			If (MyArray [Index1] > MyArray [Index1 + 1])
				Float SwapDummy = MyArray [Index1]
				MyArray [Index1] = MyArray [Index1 + 1]
				MyArray [Index1 + 1] = SwapDummy
			EndIf
			Index1 += 1
		EndWhile
		Index2 -= 1
	EndWhile
 
EndFunction

The same code can be used for moving all 'none' entries at the end of an array. For an array of forms, this would look as follows:

Function SortArray (Form[] MyArray)
 
Int Index1
Int Index2 = MyArray.Length - 1
 
	While (Index2 > 0)
		Index1 = 0
		While (Index1 < Index2)
			If (MyArray [Index1] == None)
				MyArray [Index1] = MyArray [Index1 + 1]
				MyArray [Index1 + 1] = None
			EndIf
			Index1 += 1
		EndWhile
		Index2 -= 1
	EndWhile
 
EndFunction


Making effective use of the Find function for quickly manipulating specific values in an array

Function ManipulateArrayValues (Int[] MyArray, Int ValueToFind)
 
Int Index
Int MaxIndex = MyArray.Length
 
	While (Index >= 0) && (Index < MaxIndex)
		Index = MyArray.Find (ValueToFind, Index)		
		If (Index >= 0)
                        ;Do stuff here with MyArray [Index]
			Index += 1
		EndIf
	EndWhile
 
EndFunction