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….
Browse the notebook
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….
function randomize(a:*, b:*):int{
return Math.round(Math.random()*8) - 4;
}
var i:int;
var fruits:Array;
trace("Math.random()");
for (i = 0; i<4; i++){
// reset fruits array:
fruits = ["apple", "grape","pear","cherry"];
fruits.sort(randomize);
trace(fruits);
}
// seeds
var s1:Number= 0xFF00FF;
var s2:Number = 0xCCCCCC;
var s3:Number= 0xFF00F0;
function tRandomize(a:*, b:*):int{
return Math.round(rand()*8) - 4;
}
trace("nTausworthe rand()");
for (i= 0; i<4; i++){
fruits = ["apple", "grape","pear","cherry"];
fruits.sort(tRandomize);
trace(fruits);
}
// from www.ams.org/mcom/1996-65-213/S0025-5718-96-00696-5/S0025-5718-96-00696-5.pdf
function rand():Number {
s1=((s1&4294967294)<<12)^(((s1<<13)^s1)>>19);
s2=((s2&4294967288)<<4)^(((s2<<2)^s2)>>25);
s3=((s3&4294967280)<<17)^(((s3<<3)^s3)>>11);
var r:Number = (s1^s2^s3) * 2.3283064365e-10;
r = (r<0) ? r+=1 : r;
return r;
}
/*
outputs:
Math.random()
grape,apple,pear,cherry
pear,cherry,apple,grape
grape,apple,pear,cherry
grape,apple,cherry,pear
Tausworthe rand()
apple,grape,pear,cherry
cherry,grape,pear,apple
grape,apple,cherry,pear
grape,pear,apple,cherry
*/
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()
var words:String = "one two three four five";
trace("two: ", words.indexOf("two"));
var letters:String = "abcd";
trace("d: ",letters.indexOf("d"));
trace("z: ",letters.indexOf("z"));
/*
outputs:
two: 4
d: 3
z: -1
*/
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.
var input:String = "a, b, c";
var words:Array = input.split(", ");
var max:String = "";
var maxD:String = (words.length - 1).toString();
for (var i:int = 0; i<words.length; i++){
max += maxD;
}
var maxInt:int = parseInt(max,words.length);
for(i = 0; i<=maxInt; i++){
var indices:String = i.toString(words.length);
var r:String = "";
var k:int=0;
for (var j:int = 0; j<indices.length; j++){
r += words[parseInt(indices.charAt(j))] +" ";
k++;
}
while(k < words.length) {
r = words[0] +" "+ r;
k++;
}
trace(r);
}
trace(i, " variations");
Like many things on this site, I coded this rather quickly and it can probably be cleaned up…
Setting the input variable of the above snippet to “a, b” will output:
a a
a b
b a
b b
4 variations
Setting the input to “a, b, c” will output:
a a a
a a b
a a c
a b a
a b b
a b c
a c a
a c b
a c c
b a a
b a b
b a c
b b a
b b b
b b c
b c a
b c b
b c c
c a a
c a b
c a c
c b a
c b b
c b c
c c a
c c b
c c c
27 variations
I created this to work with words… inputs like “bread, breath, blobs, backwards”. Be careful because you can quickly get millions of outputs:
1 to the power of 1 is 1
2 to the power of 2 is 4
3 to the power of 3 is 27
4 to the power of 4 is 256
5 to the power of 5 is 3125
6 to the power of 6 is 46,656
7 to the power of 7 is 823,543
8 to the power of 8 is 16,777,216
etc…
g=graphics;
mt=g.moveTo;
lt=g.lineTo;
ls=g.lineStyle;
m=Math;
r=m.random;
s=m.sin;
i=0;
o={};
function f(e){
s=150,x=y=s,z=-s,c=(!i)?addChild(new Bitmap(new BitmapData(s,s))).bitmapData:c;while(i<22500)i++,c.setPixel(i%s,i/s,(i%s|i/s)*mouseX);i=1;
}
addEventListener("enterFrame",f);
Have to link to this very fun new contest:
http://tweetcoding.machine501.com/
http://gskinner.com/playpen/tweetcoding.html
I may just have to get a twitter account…
var clock:Sprite = Sprite(addChild(new Sprite()));
clock.x = clock.y = 150;
var bg:Shape = Shape(clock.addChild(new Shape()));
with (bg.graphics) lineStyle(2, 0x666666), beginFill(0xEFEFEF), drawCircle(0,0,110);
var hHand:Shape = clockHand(6, 50);
var mHand:Shape = clockHand(2, 80);
var sHand:Shape = clockHand(1, 90);
var center:Shape = Shape(clock.addChild(new Shape()));
with (center.graphics) beginFill(0x000000), drawCircle(0,0,5);
var hInc:Number = 360/24;
var msInc:Number = 360/60 ;
var nOff:Number = 6;
var verdana:TextFormat = new TextFormat("Verdana", 8);
// add numbers to clock
for (var i:int = 0; i<24; i++){
var ang:Number = (i * hInc - 90) * Math.PI/180;
createNumber(70,ang, i.toString());
var ms:Number = i * 2.5;
if (ms % 5 == 0){
createNumber(95, ang, ms.toString());
}
}
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
var date:Date = new Date();
hHand.rotation = hInc * date.getHours();
mHand.rotation = msInc * date.getMinutes();
sHand.rotation = msInc * date.getSeconds();
}
function clockHand(thickness:Number, leng:Number):Shape{
var hand:Shape = Shape(clock.addChild(new Shape()));
with (hand.graphics) {
lineStyle(thickness, 0x000000, 1, true, LineScaleMode.NORMAL, CapsStyle.SQUARE);
lineTo(0,-leng);
}
return hand;
}
function createNumber(radius:Number, theta:Number, str:String):void{
var t:TextField = TextField(clock.addChild(new TextField()));
with (t) defaultTextFormat = verdana, t.autoSize = "left";
t.text = str;
t.x = radius * Math.cos(theta) - nOff;
t.y = radius* Math.sin(theta) - nOff;
}
I was watching a movie the other day and I saw a 24 hour clock in the background of one of the shots. After the movie I coded this snippet. It draws a very basic clock with an hour hand that takes 24 hours to go full circle…

addChild(new TextField()); getChildAt(0)["text"] = "Hello World";
Notice that square bracket syntax makes it so we don’t need to typecast. Take a look at the other way:
addChild(new TextField()); TextField(getChildAt(0)).text = "Hello World";
Typecasting is the way to go…. the square bracket technique is just an interesting trick.
I wrote this after somehow stumbling on this very entertaining page – it shows hello world written in approximately 200 different languages…
[SWF(width = 600, height = 400)]
// draw the same grid as yesterday
var tileSize:int = 40;
var cols:int = stage.stageWidth / tileSize;
var rows:int = stage.stageHeight / tileSize;
var grid:Sprite = Sprite(addChild(new Sprite()));
grid.graphics.lineStyle(0,0x000000);
var i:int = 0;
for (i = 1; i<cols; i++){
var posX:Number = i * tileSize
grid.graphics.moveTo(posX, 0);
grid.graphics.lineTo(posX, stage.stageHeight);
}
for (i = 1; i<rows; i++){
var posY:Number = i * tileSize
grid.graphics.moveTo(0, posY);
grid.graphics.lineTo(stage.stageWidth, posY);
}
//
// -- add a circle that snaps to the grid when dragged
//
var circle:Sprite = Sprite(addChild(new Sprite()));
with (circle.graphics) beginFill(0xFF0000), drawCircle(0,0,10);
circle.x = circle.y = tileSize * 3;
circle.buttonMode = true;
circle.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(evt:MouseEvent):void {
addEventListener(Event.ENTER_FRAME, onRunSnapping);
}
function onRunSnapping(evt:Event):void {
circle.x = Math.round(mouseX / tileSize) * tileSize;
circle.y = Math.round(mouseY / tileSize) * tileSize;
}
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
function onUp(evt:MouseEvent):void {
removeEventListener(Event.ENTER_FRAME, onRunSnapping);
}
This builds on yesterdays post by adding a draggable red circle that snaps to the grid. This is the real trick:
circle.x = Math.round(mouseX / tileSize) * tileSize; circle.y = Math.round(mouseY / tileSize) * tileSize;
// try changing the size of the stage
[SWF(width = 600, height = 400)]
// try changing the tile size (make sure swf width and height are evenly divisible by this number)
var tileSize:int = 20;
var cols:int = stage.stageWidth / tileSize;
var rows:int = stage.stageHeight / tileSize;
var grid:Sprite = Sprite(addChild(new Sprite()));
grid.graphics.lineStyle(0,0x000000);
var i:int = 0;
for (i = 1; i<cols; i++){
var posX:Number = i * tileSize
grid.graphics.moveTo(posX, 0);
grid.graphics.lineTo(posX, stage.stageHeight);
}
for (i = 1; i<rows; i++){
var posY:Number = i * tileSize
grid.graphics.moveTo(0, posY);
grid.graphics.lineTo(stage.stageWidth, posY);
}
This is a quick way to fill the stage with a grid. I like my grids to have square tiles with sizes like 5×5, 10×10 20×20 etc…. So as long as you make sure that you’re swf width and height are evenly divisible by your tileSize, this snippet will work nicely.
// best thing about this are the random seeds
var s1:Number= 0xFFFFFF;
var s2:Number = 0xCCCCCC;
var s3:Number= 0xFF00FF;
// saw this algorithm on this somewhat annoying thread:
// http://www.reddit.com/r/programming/comments/7yjlc/why_you_should_never_use_rand_plus_alternative/
// additional googling brought me to this: http://wakaba.c3.cx/soc/kareha.pl/1100499906/
// and finally to this ( didn't understand most of this one) www.ams.org/mcom/1996-65-213/S0025-5718-96-00696-5/S0025-5718-96-00696-5.pdf
function rand():Number {
s1=((s1&4294967294)<<12)^(((s1<<13)^s1)>>19);
s2=((s2&4294967288)<<4)^(((s2<<2)^s2)>>25);
s3=((s3&4294967280)<<17)^(((s3<<3)^s3)>>11);
var r:Number = (s1^s2^s3) * 2.3283064365e-10;
r = (r<0) ? r+=1 : r;
return r;
}
// see a visual comparison between this and actionscript's Math.random()
var canvas:BitmapData = new BitmapData(400,400,false, 0xCCCCCC);
addChild(new Bitmap(canvas));
var posX:Number;
var posY:Number;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
for (var i:int = 0; i<100; i++){
posX = rand() * 180
posY = rand() * 180
canvas.setPixel( 100 + posX, 10 + posY, 0x000000);
}
for (i = 0; i<100; i++){
posX = Math.random() * 180
posY = Math.random() * 180
canvas.setPixel( 100 + posX, 210 + posY, 0x000000);
}
}
The above snippet demo’s an alternative random number generator that uses the Tausworthe method.

Top square is Tausworthe and bottom is Math.random()
I don’t actually know much about this, or fully understand how it works. I just saw it on a random reddit thread, googled about it for a few minutes and then ported it to actionscript.
There’s lots of talk about what the BEST random number generator is…. which one is the fastest, which one is the most random. etc… I don’t really know much about that, especially since I’m just playing around with code and I don’t need a RNG for some scientific experiment. For me, what’s nice about this approach is the three random seeds. For some reason, Math.random() doesn’t have a place where you can enter a seed for random numbers. Random seeds are very useful when you want to do something random but want to be able to replicate the random results at a later time. For instance:
var s1:Number= 0xFFFFFF;
var s2:Number = 0xCCCCCC;
var s3:Number= 0xFF00FF;
trace("first three values:");
trace(rand());
trace(rand())
trace(rand())
s1 = 0xFF;
s2 = 0xEFEFEF;
s3 = 19008;
trace("nfirst three values with different seeds:");
trace(rand());
trace(rand())
trace(rand())
s1 = 0xFFFFFF;
s2 = 0xCCCCCC;
s3 = 0xFF00FF;
trace("noriginal three values:");
trace(rand());
trace(rand())
trace(rand())
function rand():Number {
s1=((s1&4294967294)<<12)^(((s1<<13)^s1)>>19);
s2=((s2&4294967288)<<4)^(((s2<<2)^s2)>>25);
s3=((s3&4294967280)<<17)^(((s3<<3)^s3)>>11);
var r:Number = (s1^s2^s3) * 2.3283064365e-10;
r = (r<0) ? r+=1 : r;
return r;
}
/*
outputs:
first three values:
0.051455706589931385
0.050584114155822715
0.417276361484596
first three values with different seeds:
0.6032885762463134
0.9319786790304015
0.8631882804934321
original three values:
0.051455706589931385
0.050584114155822715
0.417276361484596
*/
I stumbled upon a bunch of other random number algorithms, maybe I’ll throw them in a class in the next couple days.