SitePoint Sponsor

User Tag List

Results 1 to 8 of 8

Thread: random sort

  1. #1
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    random sort

    I'm looking for a script able to mix an array randomly...
    I can sort an array without any problem...
    Now I want to mix it randomly ...

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    Array.prototype.shuffle = function() {
    	for(var i = 0; i < this.length; i++) {
    		var n = Math.floor(Math.random() * this.length);
    		var tmp = this[i];
    		this[i] = this[n];
    		this[n] = tmp;
    	}
    	return this;
    }
    
    alert([0, 1, 2, 3, 4].shuffle())

  3. #3
    He's No Good To Me Dead silver trophybronze trophy stymiee's Avatar
    Join Date
    Feb 2003
    Location
    Slave I
    Posts
    23,423
    Mentioned
    2 Post(s)
    Tagged
    1 Thread(s)
    Off Topic:

    A frog helping another frog. Gotta love it.

  4. #4
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you just had to leap on that one

  5. #5
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you stereoBrother, but I don't like the tmp swapping stuff ...
    I was more thinking of something like this:

    Code:
    <script>
    Myarray=[['one','one'],['two','two'],['three','three'],['four','four'],['five','five']]
    
    function Randmix()
    {
    return Math.pow(-1, Math.round(2*Math.random()))
    }
    
    alert(Myarray.sort(Randmix))
    </script>
    But I am not satisfied of the RandMix part ...
    isn't there some byte function that would do the job ??

  6. #6
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You shouldn't use sort for this.

  7. #7
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    why if I modify the sorting order each time ... ?

  8. #8
    SitePoint Addict
    Join Date
    May 2004
    Location
    Europe
    Posts
    216
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your function is not a consistent comparison function. Theoretically several bad things could happen when you use sort() this way.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •