P
ROTOTYPE
I'm Not Only The Prototype, I'm Also A Member.
home
▪
stats
▪
search
▪
linkback
▪
about
▪
FAQ
| user: guest,
login
,
register
Array
:
Array.prototype.random
author:
black
[+]
,
Submitted: 05.20.03 8p
• Last Edit: 06.07.03 1a
/************** Array.prototype.random ***************** Flashed by black Description: By invoking this method you will get random elements of the caller array~ ********************************************************/ Array.prototype.random = function() { var len = this.length; var temp = new Array(); for (var i=0; i<len; i++) { var ran = Math.round(Math.random() * (this.length - 1)); // this.length is required because we need a dynamic digit here~ temp[i] = this[ran]; this.splice(ran, 1); } // Reassign values to original array~ for (var j=0; j<len; j++) { this[j] = temp[j]; } }
usage
[b]No parameters needed, this method will work the caller array~[/b] Example: [code] arr = [ 1, 2, 3, 4, 5 ]; arr.random(); trace(arr); // Check the result~ [/code]
msg
1
{
zipnedles
[+]
, posted: 05.23.03 6p•-, top
[^]
}
another solution:
Array.prototype.random = function() { var r = []; var t = this.length; for(var i = 0; i < t; r[i++] = this.splice(Math.floor(Math.random()*this.length),1) ); for(var j=0;j<t;j++) this[j] = r[j]; return this; } // var a = [0,1,2,3,4,5]; a.random(); trace(a);
msg
2
{
tumetom
[+]
, posted: 05.26.03 1p•-, top
[^]
}
and another:
Array.prototype.random=function(){ this.sort(function(){return Boolean(random(2))}); return true }
msg
3
{
iv
[+]
, posted: 10.12.05 7a•-, top
[^]
}
this method faster more than 100 times than method in previous post:
Array.prototype.shuffle = function() { var len = this.length; var i = len while (i--) { var j = random(len); var n = this[j]; this[j] = this[i]; this[i] = n; } }; // TEST arr = []; i = 10000; while (i--) { arr[i] = i } t = getTimer(); arr.shuffle(); trace((getTimer()-t));
Add Comment
[+]
›opyleft 2001-2010. Layer51 is: Jaime Prado.
@