Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何随机填充矩阵的行?_Javascript_Arrays_Matrix_Random - Fatal编程技术网

Javascript 如何随机填充矩阵的行?

Javascript 如何随机填充矩阵的行?,javascript,arrays,matrix,random,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

我有一个包含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"
let matrix=[];
设matrixRows=3;
设matrixColumns=5;
for(设i=0;i
您可以通过以下步骤完成此操作:

  • 首先创建一个函数,该函数采用两个参数
  • 然后创建一个helper函数
    shufflearlay
    ,该函数将数组作为参数,并返回一个新数组,该数组被洗牌
  • 在main函数中,为
    cols
    的编号创建一个数字数组。在这种情况下,它将是
    [1,2,3,4,5]
    。您可以使用
    map()
  • 然后创建一个长度等于给定
    行的
    未定义的
    数组
    
  • 在上面使用
    map()
    ,并返回我们之前创建的新无序数组(
    [1,2,3,4,5]
函数随机播放(arr){
//创建阵列的副本
arr=arr.slice();
//创建一个数组,其中将添加来自“arr”的随机项
设res=[];
//创建while循环,该循环将一直运行,直到删除arr中的所有元素
while(arr.length){
//在“arr”的长度范围内生成随机索引
设i=Math.floor(arr.length*Math.random())
//将该索引处的元素推送到结果数组
再推(arr[i]);
//从原始数组中删除该元素,即“arr”
阵列拼接(i,1);
}
返回res;
}
函数矩阵(行、列){
//创建一个反复洗牌的数组。
设genArr=[…数组(cols)].map((x,i)=>i+1);
return[…数组(行)]//创建长度等于行的未定义数组
.map(x=>shuffleArray(genArr))//将每个数组更改为另一个无序数组。
}

console.log(randMatrix(3,5).join('\n'))
您可以使用创建多达
矩阵列的数字数组。然后在每次迭代中随机洗牌数组并创建行()

//https://stackoverflow.com/a/18806417/3082296
函数洗牌(arr){
设i=arr.length,
复制=[…arr],//复制一份
输出=[];
而(我--){
常数j=数学楼层(数学随机()*(i+1));
输出推送(复制拼接(j,1)[0]);
}
返回输出
}
设矩阵=[];
设matrixRows=3;
设matrixColumns=5;
//自然数到矩阵列
const numbers=Array.from({length:matrixColumns},(\ux,i)=>++i)
const output=Array.from({length:matrixRows},=>shuffle(数字))

console.log(output)
不是最优雅的,但这首先创建了一个唯一随机数的平面列表,并将其简化为二维n*m矩阵:

函数fillRand(n,m){
设rands=[];
做{
var rand=Math.random();
}而(!~rands.indexOf(rand)和&rands.push(rand){
让我们坚持下去;
如果(i%n==0){
垫推([]);
}
最后一个=材料[材料长度-1]
last.push(cur);
返回垫;
},[])
}

console.log(fillRand(4,5))
它是否总是一个3x5列,随机数介于1和5之间?可能是