如何随机填充矩阵的行?

时间:2019-05-29 18:34:09

标签: javascript arrays matrix random

我有一个包含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"

3 个答案:

答案 0 :(得分:0)

您可以按照以下步骤进行操作:

  • 首先创建一个带有两个参数rowscols的函数
  • 然后创建一个辅助函数shuffleArray,该函数将数组作为参数并返回经过改组的新数组。
  • 在主函数中,为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'))

答案 1 :(得分:0)

您可以使用Array.from()创建最多matrixColumns的数字数组。然后在每次迭代中随机地对数组进行随机排序,并创建行(from this answer

// https://stackoverflow.com/a/18806417/3082296
function shuffle(arr) {
  let i = arr.length,
    copy = [...arr], // take a copy
    output = [];

  while (i--) {
    const j = Math.floor(Math.random() * (i + 1));
    output.push(copy.splice(j, 1)[0]);
  }
  return  output
}

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

// Natural numbers upto matrixColumns
const numbers = Array.from({ length: matrixColumns }, (_, i) => ++i)
const output = Array.from({ length: matrixRows }, _ => shuffle(numbers))

console.log(output)

答案 2 :(得分:0)

这不是最优雅的方法,但这首先创建了一个唯一随机变量的平面列表,并将其简化为2d n * m矩阵:

function fillRand (n, m) {
      let rands = [];
      do {
    	var rand = Math.random ();
      } while (!~rands.indexOf (rand) && rands.push (rand) < n*m);
    
      
      return rands.reduce ((mat, cur, i) => {
    	 let last;
         if (i%n==0) {
            mat.push ([]);
         }
     	 last = mat[mat.length - 1]
         last.push (cur);
         return mat;
      },[])
    }

console.log (fillRand (4,5))