-
var letterA:String = "a";
-
var letterZ:String = "z";
-
-
trace(letterA.localeCompare(letterZ));
-
trace(letterZ.localeCompare(letterA));
-
/*
-
outputs
-
-25
-
25
-
*/
String.localeCompare() calculates the sorting order between two Strings....
String.localeCompare() calculates the sorting order between two Strings....
The above shows how to randomly sort or shuffle an array. This is useful in games. To achieve this I made use of the compareFunction argument of Array.sort(). Most sorting algorithms go through the array and compare values until the desired sort order is achieved. The compareFunction argument is a function that takes two values a and b and returns an integer that is negative positive or zero... see this info from the docs:
* A negative return value specifies that A appears before B in the sorted sequence.
* A return value of 0 specifies that A and B have the same sort order.
* A positive return value specifies that A appears after B in the sorted sequence.
So in the case of a randomizing an array you simply need to return a random int -1, 0 or 1. This is what I've done in the past (Math.round()*2) -1) ... but when I was writing this snippet it seemed like 0 caused less variation in the output of the array so I made the range from -4 to 4 instead. This could have just been my imagination, but it seems like having less chance of a zero caused the arrays to be a bit more shuffled.
The reason I also included a version that uses Tausworthe is because of the easy seeding. In some cases you may want to use seeded randomness to sort an array.
UPDATE:
Was digging around about this and found a much faster method for randomizing arrays... not a big deal if you have small arrays, but if you need to randomize 1000's of values this method is much faster than using Array.sort()
indexOf() searches a string for another string and returns an index... in line 3 above, I search the words string for the smaller string "two" and indexOf() gives me the index of the letter "t". If indexOf() doesn't find anything it will return -1 (as in the case of line 9).
I seem to recall using this in some unexpected places. I'll see if I can dig up an example over the next few days.
The above animates a zig zag pattern in a TextField.