0

I think I'm misunderstanding something about variable scope in JavaScript. The goal is, given an array of numbers, to generate a 2D array that contains all the rotations of that array. So, the array [1,2,3,4] should yield a 2D array of:

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

I'm coming from Ruby, where the following would work just fine:

row = [3,1,6,4];

function rotations(arr) {
  var rotations = [];
  var i = 0;
  var k = arr.length;
  while(i < k) {
    arr.unshift(arr.pop());
    rotations.push(arr);
    i++;
  };
  return rotations;
};

console.log(rotations(row));

However, what this logs is a 2D array containing 4 iterations of the original array:

[ [ 3, 1, 6, 4 ], [ 3, 1, 6, 4 ], [ 3, 1, 6, 4 ], [ 3, 1, 6, 4 ] ]

So it appears that the original array row is not being modified in the scope of the function - only in the scope of the nested while loop.

1 Answer 1

2

You just need to copy your array before modifying it with unshift, because it modifies origin array

var row = [3,1,6,4];

function rotations(arr) {
  var rotations = [arr];
  var i = 1;
  var k = arr.length;
  var copiedArr = arr
  while(i < k) {
    copiedArr = [...copiedArr]
    copiedArr.unshift(copiedArr.pop());
    rotations.push(copiedArr);
    i++;
  };
  return rotations;
};

console.log(rotations(row));
console.log(rotations([1,2,3,4]))

More about unshift is here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

Or if you need the first element also being rotated

var row = [3,1,6,4];

function rotations(arr) {
  var rotations = [];
  var i = 0;
  var k = arr.length;
  var copiedArr = arr
  while(i < k) {
    copiedArr = [...copiedArr]
    copiedArr.unshift(copiedArr.pop());
    rotations.push(copiedArr);
    i++;
  };
  return rotations;
};

console.log(rotations(row));
console.log(rotations([1,2,3,4]))

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, this makes a ton of sense! Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.