[Tfug] random squares
Robert Hunter
hunter at tfug.org
Mon Oct 22 00:20:21 MST 2007
On 10/21/07, Robert Hunter <hunter at tfug.org> wrote:
> On 10/21/07, christopher floess <skeptikos at gmail.com> wrote:
>> I know I could use math.random(), but
>> would anyone recommend a better way to do this?
>
> This is especially nice if a "shuffle" function is
> already provided for you.
A Knuth shuffle in less than ten lines of JavaScript.
<snip language="JavaScript">
// randomize the order of an array
function shuffleArray(ary) {
if (ary.length == 1) {
return ary;
} else {
var n = Math.floor(Math.random() * ary.length);
var x = ary.splice(n, 1);
var y = shuffleArray(ary);
y.push(x[0]);
return y;
}
}
</snip>
PS. It's probably a one-liner in Perl ;-)
--
RH
More information about the tfug
mailing list