簡體   English   中英

使用隨機 0 和 1 值創建矩陣的代碼

[英]Code that creates matrix with random 0 and 1 values

你能寫一個用0或1隨機填充空矩陣的js代碼嗎? 我需要使用 Random() 函數。

我寫了這段代碼,但出現錯誤 Random() is not defined

var matrix = [];


for(var y = 0; y<5; y++){
    for(var x = 0; x<5; x++){
        let arr = [0,1]
     matrix[y][x]= random(arr)
      matrix.push(matrix[y][x])
    }
}

您應該Math.random()然后使用Math.round()來獲取01 其次,您應該將matrix[y]設置為空數組,否則代碼將引發錯誤。

 var matrix = []; for(var y = 0; y<5; y++){ matrix[y] = []; for(var x = 0; x<5; x++){ matrix[y][x]= Math.round(Math.random()) matrix.push(matrix[y][x]) } } console.log(matrix) 

可以使用map()輕松創建任意長度的矩陣。 創建一個給定長度的數組,並將其映射到另一個具有相同長度且長度從01數組

 const getMatrix = len => [...Array(len)].map(x => [...Array(len)].map(b => Math.round(Math.random()))); let res = getMatrix(5); console.log(res) 

對於不同的長度和寬度,請使用兩個參數。

 const getMatrix = (l,w) => [...Array(l)].map(x => [...Array(w)].map(b => Math.round(Math.random()))); let res = getMatrix(2,3); console.log(res) 

您應該使用Math.round(Math.random())

使用 ES6 的一種簡單方法:

 const arr = new Array(5).fill().map(() => new Array(5).fill().map(() => Math.round(Math.random()))); console.log(arr);

您必須在map()之前使用fill()方法,否則您將獲得未定義的值。

使用您的代碼片段執行此操作的“經典”方法將類似於您嘗試的方法,添加了標准內置對象Math ,該對象具有random()方法和round()以獲取整數值。 如果你想要一個矩陣(二維數組),那么你需要將一個數組推入每一行,否則你將得到一個簡單的數組。

 var matrix = []; for(var y = 0; y < 5; y++) { const row = []; for(var x = 0; x < 5; x++) { row.push(Math.round(Math.random())); } matrix.push(row); } console.log(matrix);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM