Very short snippet: shuffle () in Javascript and Actionscript

In PHP there is a handy feature called shuffle() that allows you to mix an array (see Very short trick: take random elements from an array in PHP ). An excellent version of the javascript I found here . Slightly revised the code below:

1
2
3
= function ( ) { Array. Prototype. Shuffle = function () {
var j , x , i = this . length ; i ; j = Math. floor ( Math. random ( ) * i ) , x = this [ -- i ] , this [ i ] = this [ j ] , this [ j ] = x ) ; for (var j, x, i = this. length, i, j = Math. floor (Math.E random () * i), x = this [- i], this [i] = this [j], this [j] = x);
}

al posto di parseInt() , in quanto da test effettuati è risultato estremamente più veloce, almeno sulla mia macchina e con FireFox 3. Compared to the original I have extended the object Array and placed Math.floor() instead of parseInt() , because from our tests was very fast, at least on my machine and with FireFox 3.

In ActionScript 3.0, I used the classroom MatrixArray :

1
2
3
4
5
6
7
8
/ **
* Mix in a random matrix
*
* /
shuffle ( ) : void { public function shuffle (): void {
/ / Thanks to http://jsfromhell.com/array/shuffle
var j , x , i = __len ; i ; j = Math . floor ( Math . random ( ) * __len ) , x = this [ -- i ] , this [ i ] = this [ j ] , this [ j ] = x ) ; for (var j, x, i = __len, i, j = Math . floor ( Math . random () * __len), x = this [- i], this [i] = this [j], this [j ] = x);
}

4 comments: "Very short snippet: shuffle () in Javascript and Actionscript"

  1. April 2, 2009 Very short snippet: Actionscript extend an array by the method shuffle () | Undolog.com :

    [...] Already talked about how to implement the method shuffle () in Javascript and Actionscript. I realized, tuttaavia, not pointing out that Actionscript is able to [...]

  2. April 2, 2009 DaveOnCode :

    This is my own solution: http://www.daveoncode.com/2009/01/08/implementing-arrayshuffle-in-actionscript/

    It's only 3 lines of code and it works fine :)

  3. April 2, 2009 Giovambattista Fazioli :

    @ DaveOnCode: very short snippets :) thx

  4. October 26, 2010 Objective-C: subclassing and Categories | Undolog.com :

    [...] As seen in the Very short snippet: shuffle () in Javascript and Actionscript. [...]

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL 


Stop SOPA