0

I am trying to shuffle an array and add the shuffled-set every time into 2D array using a loop. the problem is that the resulted 2D array contains the same shuffled-set for all rows, while the output of each shuffled-set is different.

So; what do I miss here?

var b=[1,2,3,4,5,6,7,8,9];
var matrix=[];

for(var i=0; i <5; i ++){
    shuffle(b);
    matrix[i]=b;
    //matrix.push(b);
    console.log(b);
}
console.log(matrix);


function shuffle(array) {
    var ctr = array.length, temp, index;
    while (ctr > 0) {
        index = Math.floor(Math.random() * ctr);
        ctr--;
        temp = array[ctr];
        array[ctr] = array[index];
        array[index] = temp;
    }
    return array;
}

the output:

Array(9) [ 7, 3, 4, 9, 2, 1, 6, 8, 5 ]
Array(9) [ 5, 6, 3, 9, 8, 4, 1, 7, 2 ]
Array(9) [ 9, 5, 2, 4, 3, 6, 8, 7, 1 ]
Array(9) [ 3, 5, 2, 1, 4, 9, 6, 8, 7 ]
Array(9) [ 5, 9, 4, 6, 7, 3, 2, 8, 1 ]

(5) […]
0: Array(9) [ 5, 9, 4, … ]
1: Array(9) [ 5, 9, 4, … ]
2: Array(9) [ 5, 9, 4, … ]
3: Array(9) [ 5, 9, 4, … ]
4: Array(9) [ 5, 9, 4, … ]
length: 5

2 Answers 2

1

You only have one 1D array object, i.e. b. And you keep shuffling and adding that same object reference to matrix:

 matrix[i]=b;

So even after you have added such a row, you will keep mutating that added row when you call shuffle again.

You should take a copy of the array so you have different arrays that get added to matrix:

 matrix[i]=b.slice();

There are several ways to get a copy: b.slice() can also be Array.from(b), or [...b].

Alternatively, you could put the initalisation of b as new array, inside the loop:

var matrix = [];
for (var i = 0; i < 5; i++){
    var b = [1,2,3,4,5,6,7,8,9];
    shuffle(b);
    matrix[i] = b;
}

As you have designed shuffle to return the array also, you can reduce the above code to:

var matrix = [];
for(var i = 0; i < 5; i++){
    matrix[i] = shuffle([1,2,3,4,5,6,7,8,9]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

you could take a shallow clone of your shuffle.

 for(var i=0; i <5; i ++){
    const clone = {...shuffle(b)};
    matrix[i]=clone;
    //matrix.push(b);
    console.log(clone);
}
console.log(matrix);

1 Comment

Note that {...shuffle(b)} is not an array instance.

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.