2

How to I shuffle the order of the rows of a matrix? Here is a matrix for example:

1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18

I want to shuffle the order of the rows.

13 14 15 16 17 18
1 2 3 4 5 6
7 8 9 10 11 12

How can I do this in JavaScript?

Sharonas Ykm
  • 427
  • 2
  • 4
  • 13
  • Please provide your array in JavaScript notation. Also, why would it be any different from shuffling anything else in the array? See linked Q&A on shuffling an array. There is nothing different to it when your array contains arrays. – trincot Jun 17 '20 at 15:30
  • just take a standard shuffle algo for the outer array. – Nina Scholz Jun 17 '20 at 15:31

1 Answers1

0

You can iterate over the rows and randomly swap as follows:

let matrix = [
     [1, 2, 3, 4, 5, 6],
     [7, 8, 9, 10, 11, 12],
     [13, 14, 15, 16, 17, 18]
];
console.log( shuffleMatrix(matrix) );

function shuffleMatrix(matrix){
     for(let i = matrix.length-1; i > 0; i--){
          const j = Math.floor(Math.random() * i)
          const temp = matrix[i]
          matrix[i] = matrix[j]
          matrix[j] = temp
     }
     return matrix;
}
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48