Randomize a list

BlitzMax Forums/BlitzMax Programming/Randomize a list

siread(Posted 2006) [#1]
Is there an easy way to overide the compare method so that so that i can sort a list into a completely random order?

Otherwise, what's the best way to randomize a list of objects?


siread(Posted 2006) [#2]
This seems to do the trick...

Method Compare(O:Object) 'Override Original Compare
		Select SortBy
		Case CSORT_RANDOM
			If Rand(list.Count()/2) = 1 Then Return -1 Else Return 1
		EndSelect
	EndMethod


It's slower than a normal sort but it gets the job done. :)


Gabriel(Posted 2006) [#3]
Might that not be dangerous? Is there not a very, very, very slight chance that it could take a VERY long time to sort that?

I just cycle through every object in the list, give them a random number and then sort by the field I put the random number in.


tonyg(Posted 2006) [#4]
Use the Sortlist function but with a specific comparefunc paramater. Thay way the official compare can work as normal.


taxlerendiosk(Posted 2006) [#5]
The correct way to randomize a list of elements is to go through each element from first to list and swap it with a random element between that element and the last element in the list. It might seem counterintuitive to do it that way instead of any element from the beginning to the end of the list, but it's actually right. Think of it instead as, you first choose the first element from anywhere in the list. Then, you choose the second element only from what's left - the first element has already been chosen. And so on.

However, I'm not actually sure of the correct way to swap two elements in a list in BlitzMax. I feel like I want to make an array of the TLink objects and then mess with them in order to do it, but there's probably an official way.


tonyg(Posted 2006) [#6]
If you didn't want to use comparefunc you could do listtoarray, shuffle the array and then listfromarray to move it back?