Oct
16
2009

Random sort function comes handy when building applications with playlists

When you want to create application that would use something like a playlist where all the songs are in random order and each song should be picked up only one time in a row until the whole cycle is finished, then you should use array's sort method with custom sort function.

It may appear funny that to create a random order you should use a sort function. But actually what you are doing is you are using random sort order. By default when using sort method on arrays without passing any argument, it will sort an array alphabetically unless you use Array.DESCENDING or other constants. But you can pass name of your own custom sort "compare" function that will take two arguments, two values that will be compared and will return a negative value if first value is selected or a positive value if second value is selected.

So to build your playlist, first I will create an array of songs. This  could be names of your songs or links to music files. Next I will create a new array that will have the same number of items as my array with songs and will be populated with values from 0 to array length - 1. Next I will sort this array using my custom compare function. After that I will iterate this array to get an index to get my songs from the songs array. This will be of course a random order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//first create your array with songs
var songsArray:Array = new Array();
songsArray.push("Various Artist - Song1.mp3");
//...etc
 
//next create random array
for (var i:int = 0; i < songsArray.length; i++) 
{
    pickArray[i] = i;
}
//and sort it with your custom sort function
pickArray.sort(randomSort);
 
function randomSort(elementA:Object, elementB:Object):int 
{
    return Math.random() * 10 - 5;
}
 
//let say playNextSong function is initiated 
//by the user clicking on "next" button
var counter:uint = 0;
function playNextSong(e:MouseEvent):void
{
	//pick some random song but make sure we won't go out of range
	counter = (counter == songsArray.length - 1) ? 0 : counter + 1;
	playSong(songsArray[pickArray[counter]]);
}

 

Comments 

 
-1 #1 Anthony 2011-01-16 19:15
That's a good one, thanks! Just copied and pasted it to my JavaScript code and it works.
Quote
 

AS3 Tips

Follow me on Twitter