Actually I first started using Martin's algorithm, but felt uneasy
because it seems as the outcome depends on the sorting algorithm used.
But Thomas' version doesn't so I'll stick with his (and it's as short
as it gets). Thanks a lot
I still insist that a shuffle method for Array, (or even Enumerable?)
should be part of the Prototype library, isn't this the place to
suggest additions?
On May 24, 7:30 pm, Thomas Fuchs <[EMAIL PROTECTED]> wrote:
> Array.prototype.shuffle = function(){
> return this.sortBy(Math.random);
>
> }
>
> Note that the above has a (near impossible) chance to result in an
> endless loop.
>
> Best,
> Thomas
>
> Am 24.05.2007 um 19:09 schrieb Martin Ström:
>
>
>
> > Here's a shorter version (wont change the current array but return a
> > new, shuffled, copy:
>
> > Object.extend(Array.prototype, {
> > shuffle: function() {
> > return this.sort(function() {
> > return Math.floor(Math.random() * 3 -1);
> > });
> > }
> > });
>
> > /Martin
>
> > On 5/24/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> >> I needed to shuffle an array, but there was no method so I made one.
> >> Maybe this could be added? I have tested it only on Firefox.
> >> Array.prototype.shuffle = function() {
> >> var j = null // random index from i to last
> >> for (var i=0; i < this.length; ++i) {
> >> j = Math.floor(Math.random()*(this.length-i)) + i
> >> var tmp = this[i]
> >> this[i] = this[j]
> >> this[j] = tmp
> >> }
> >> return this
> >> }
>
> > --
> > burnfield.com/martin
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Spinoffs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---