javascript - 如何随机填充矩阵的行?
问题描述
我有一个包含 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"
解决方案
您可以通过以下步骤执行此操作:
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'))
推荐阅读
- kendo-ui-angular2 - 在 Kendo 上传组件中隐藏文件列表
- node.js - 具有自定义属性的文件对象
- c++ - 无法在 Windows 7 64 位上安装 CUDA Toolkit 9.1.85
- git - 如何在项目的所有分支上更新 Unity
- python - Python(版本 3.6.3)pandas(安装版本 0.22.0)导入错误
- file-upload - 在Jmeter中为每个线程上传不同的文件
- android - 如何在 Xamarin Android 上获取任何选择文件的文件路径
- php - 使用 Laravel Eloquent 选择多个表
- php - 在自定义编译的 Apache 上安装 PHP 时出错
- c# - 如何使用 FluentValidation 验证 Guid 列表