hi,
How can I randomly sort my array?
hi,
How can I randomly sort my array?
you mean put the elements in a random order?
if so, here is a simple algorithm:
start with a sorted (or unsorted array) and swap each element at index i with an element with index >= i
function randomizeArray(arr : int[]){
for (i = 0; i < array.length; i++){
swap(arr, i, Random.Range(i,arr.length));
}
}
function swap(arr : int[], id1 : int, id2 : int){
var temp = arr[id1];
arr[id1] = arr[id2];
arr[id2] = temp;
}
JustinLloyd pointed out a major flaw with that type of sorting (I proposed the same thing) in a recent thread:
I was looking for this thread to answer another post and saw this.
I don’t understand what the ‘major flaw’ is. I wouldn’t consider swapping the last element of the array with itself to be a bug or a performance hit. I like Justin’s solution for getting random sequence of nonrepeating numbers a lot, but for randomizing an array, the function above is perfectly fine if you ask me
Initially I thought he was correct because I didn’t account for the fact that swapping the early values also moves them down the array to be reswapped later. I did a quick test and yeah, distribution is even. (randomized 10,000 arrays of length 10, and the distribution of values was 10% ± 0.5%)
So I take it back. We both wrote good scripts! (yours is better!)
Great minds think alike ![]()
Yeah, but us fools seldom differ. >.>