首页 > 解决方案 > 如何随机填充矩阵的行?

问题描述

我有一个包含 n 行和 n 列的矩阵。我需要确保每行中的数字是唯一的。

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"

标签: javascriptarraysmatrixrandom

解决方案


您可以通过以下步骤执行此操作:

  • rows首先创建一个带有两个参数的函数cols
  • 然后创建一个辅助函数shuffleArray,它接受一个数组作为参数,并返回一个被洗牌的新数组。
  • 在 main 函数中,为 的编号创建一个数字数组cols。在这种情况下,它将是[1,2,3,4,5]。您可以使用map()
  • undefined然后创建一个长度等于给定的数组rows
  • 使用map()它并返回我们之前创建的一个新的洗牌数组([1,2,3,4,5]

function shuffleArray(arr){
  //create a copy of the array
  arr = arr.slice();
  //create an array on which random items from 'arr' will be added
  let res = [];
  //create while loop which will run until all the elements from arr are removed 
  while(arr.length){
    //generate a random index in range of length of 'arr'
    let i = Math.floor(arr.length * Math.random())
    //push element at that index to result array
    res.push(arr[i]);
    //remove that element from the orignal array i.e 'arr'
    arr.splice(i,1);
  }
  
  return res;
}

function randMatrix(rows,cols){
  //create an array which will shuffled again and again.
  let genArr = [...Array(cols)].map((x,i) => i + 1);
  
  return [...Array(rows)] // create an array of undefined of length equal to rows
           .map(x => shuffleArray(genArr)) // change that each to another shuffled array.
}

console.log(randMatrix(3,5).join('\n'))


推荐阅读