2

I am able to shuffle an array with this function

function getBadlyShuffledList(list) {
  var length = list.length;
  var i;
  var j;

  while (length) {
    i = Math.floor(Math.random() * length--);


      j = list[length];
      list[length] = list[i];
      list[i] = j;

  }
  return list;
}

console.log(getBadlyShuffledList([1,2,3,4,5,6]));

The problem is I need to leave the index's that are divisible by two in their places. I tried using an if statement and it get's the index if it is 2 or 4, but then I don't know what to do to make it stay put.

For example if I have an array [1, 2, 3, 4, 5, 6] When shuffled, 3 and 5 should remain put. ex; [2, 4, 3, 1, 5, 6] How do I go about doing this?

rdeg
  • 169
  • 3
  • 15

1 Answers1

2

I borrowed a shuffle function from the following link... How to randomize (shuffle) a JavaScript array?

Build an array that contains the elements you want to shuffle. Shuffle them. And finally add each element one by one back into your original array skipping every other element. It works but there is room for optimization.

/**
 * Randomize array element order in-place.
 * Using Fisher-Yates shuffle algorithm.
 */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}


function getBadlyShuffledList(list) {

  listToShuffle = []

  for(var i=0; i < list.length; i++){
    if (i%2!==0){
      listToShuffle.push(list[i]);
    }
  }

  shuffleArray(listToShuffle);

  for(var i=0; i < list.length; i++){
    if (i%2!==0){
      list[i] = listToShuffle[0];
      listToShuffle.shift();
    }
  }

  return list;
}

console.log(getBadlyShuffledList([3, 1, 2, 3, 4, 5, 6, 6, 6, 9, 2]));
Community
  • 1
  • 1
abaldwin99
  • 903
  • 1
  • 8
  • 26
  • I'm not sure how OP intented the result, but I think this is wrong: `[3, 1, 2, 3, 4, 5, 6, 6, 6, 9, 2]` => `[3, 5, 2, 9, 4, 1, 6, 3, 6, 6, 2]` – Rudie Jul 31 '15 at 16:54
  • The way I read the OP it should be every other element stays the same starting with the first one. In your array. 3 . 2 . 4. 6. 6. 2 are all in the same position in the output with the other elements shuffled around. – abaldwin99 Jul 31 '15 at 17:02