skip to content

Archive for the ‘Code Snippets’ Category

Detecting iPhone/iPod version

In some cases it is required to change application behaviour depending on iPhone or iPod Touch device version.

#import <sys/utsname.h>;
...
struct utsname u;
uname(&u);

After calling uname() function, u.machine will be “iPod1,1″, “iPod2,1″ for iPod Touch and “iPhone1,1″, “iPhone1,2″, “iPhone2,1″ for iPhone (or similar depending on current device).

Source:

Random permutation of array

Here is the code snippet for generating random permutation of array:

var a:Array = new Array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );

trace( "Array: " + a );

for ( var i:uint = 0; i < a.length; ++i )
{
    var j:int = Math.random()*i;
    var j:int = Math.random()*( i + 1 );

    // Swap a[i] and a[j]
    var temp:* = a[j];
    a[j] = a[i];
    a[i] = temp;
}

trace( "Permutation: " + a );

Update: fixed bug with finding index of item to swap – thanks for pointing that out Kevin!

Displaying Sprite in Flex

Today I’ve tried to add simple Sprite instance to Flex Canvas using addChild() method, but it doesn’t work. Solution is very simple – use rawChildren.addChild().

⇥ Continued