Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    878
    Thanks
    0
    Thanked 114 Times in 113 Posts

    Shuffling Arrays

    Running toSource() on a shuffled array, I found that an array shuffled by
    a common function:
    Code:
    function Shuffle(Arr){
    TempArr=[];
    while(Arr.length){TempArr.push(Arr.splice(CalculatedNumber,1));}
    while(TempArr.length){Arr.push(TempArr.pop();}
    return Arr;
    }
    gains an extra dimension.
    (most shuffle functions found in these forums, are quite similar to this).

    Effect:
    Code:
    MyArray=[ImgSrc1,ImgSrc2,ImgSrc3];
    ImgElement.src=Myarray[0]; // gives: ImgElement.src=ImgSrc1;
    Shuffle(MyArray);
    ImgElement.src=Myarray[0]; // gives: ImgElement.src=[ImgSrcX];
    In spite of the extra dimension, it would still give the desired outcome.

    But sometimes multi-dimensionals array are shuffled, and then this extra dimension will cause troubles.
    (often used for banners):
    Code:
    MyArray=[[ImgSrc1,Link1],[ImgSrc2,Link2],[ImgSrc3,Link3]];
    ImgElement.src=Myarray[0][0]; // gives: ImgElement.src=ImgSrc1;
    LinkElement.href=Myarray[0][1]; // gives: LinkElement.href=ImgSrc1;
    Shuffle(MyArray);
    ImgElement.src=Myarray[0][0]; // gives: ImgElement.src=[ImgSrcX,LinkX]; OOPS!
    LinkElement.href=Myarray[0][1]; // gives: LinkElement.href=undefined; OOPS!
    Solution:
    Code:
    ... while(Arr.length){TempArr.push(Arr.splice(CalculatedNumber,1)[0]);} ...
    Addressing the above problem and wanting to use the same function for both:
    shuffling an array.
    (Usually Shuffle(MyArray);
    and
    shuffling an copy of the array (without shuffling the original array).
    (Usually MyArrayCopy = MyArray.slice(0); Shuffle(MyArrayCopy);)
    - I came up with this:
    Code:
    function shuffle(Arr){
    var NewArr=Arr.slice(0);
      var Range=NewArr.length;
      while(Range>0){
        NewArr.push(NewArr.splice(Math.floor(Math.random()*Range),1)[0]);
        Range--;
      }
      return NewArr;
    };
    Usage:
    Shuffling an array is done by: Array=shuffle(Array);
    Making a shuffled Copy is done by: ArrayCopy=shuffle(OrgArray);
    Last edited by Lerura; 06-12-2012 at 09:14 AM.

  2. Users who have thanked Lerura for this post:

    Philip M (06-12-2012)


 

Posting Permissions

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