-1

I want to rotate my entire array, for example:

[1,2,3,4] becomes [3,4,1,2]

my current function is:

function shuffle(o){ 
    for(i = 0; i<Math.floor((Math.random() * o.length)); i++){
        o.push(o.shift());
    }
};

Please tell me what I am doing wrong.

Maglor
  • 47
  • 2
  • 11
  • 2
    you want to shift **or** shuffle your array? – BeNdErR Nov 07 '14 at 15:23
  • 2
    See http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – ROMANIA_engineer Nov 07 '14 at 15:24
  • 3
    Please fix your wording. ["shift"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) has a well-defined meaning, and so does "shuffle", they are completely different. Do you want to do one, or the other? – user229044 Nov 07 '14 at 15:25
  • Please *tell us* what is wrong. What's happening? – LcSalazar Nov 07 '14 at 15:34
  • http://dzone.com/snippets/array-shuffle-javascript That should help you. – AlvinJ Nov 07 '14 at 15:36
  • 1
    @here People, you closed a question without actually letting the question's author confirm your assumptions that he is actually looking for a "shuffle". If you look at his algorithm, he's pretty clearly **rotating** the array, and his languages states he's trying to **shift** the array, so instead of editing his question so it's a duplicate and then closing it, **wait for him to clarify**. – user229044 Nov 07 '14 at 15:37
  • I'm sorry, just got the js-badge, and wasn't aware that one dup-vote is enough with that. I'll be more careful now. – Yoshi Nov 07 '14 at 15:40
  • 1
    What you want to do is called *rotating* an array (buffer). – Bergi Nov 07 '14 at 15:45
  • Yes I meant to say rotate the array, but I did not know the proper terminology – Maglor Nov 07 '14 at 19:37

2 Answers2

1
function shuffle(o){
    for(i = 0; i < o.length; i++)
     {
        var Index = o.indexOf(i);
        index=index+2;
        if(index>3)
        {
            index=index-2;
          var item=o.splice(index,1)
        o.push(item);
        }  
         else 

         {var item=o.splice(index,1)
          o.push(item)
        }        
}
};
Rahul Sharma
  • 453
  • 3
  • 10
0

Your current function just shifts it by a random amount, i.e. it offsets it by a random amount.

Instead, you want to randomly pick from the array and move that element. Try this (untested):

function shuffle(o){
    for(i = 0; i < o.length; i++){
        var randomIndex = Math.floor(Math.random() * (o.length - i));
        var item = o.splice(randomIndex, 1);
        o.push(item);
    }
};

EDIT: It seems there's some confusion about what you're trying to accomplish. My answer above assumes you mean shuffle (randomize the order of elements in the array).

Grant Amos
  • 2,256
  • 17
  • 11