Reputation: 3
Can you please write a js code that fills empty matrix randomly with 0 or 1? I need to use Random() function.
I wrote this code and I got an error 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])
}
}
Upvotes: 1
Views: 782
Reputation: 1
An easy way to do it using ES6:
const arr = new Array(5).fill().map(() => new Array(5).fill().map(() => Math.round(Math.random())));
console.log(arr);
You have to use the fill()
method before map()
, otherwise you will get undefined values.
The "classical" way to do it using your snippet of code will be similar to what you tried, with the addition of the standard built-in object Math
which has the random()
method and also round()
to get integer values. If you want a matrix (2D array) then you will need to push an array into each row, otherwise you will get a simple array.
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);
Upvotes: 0
Reputation: 36564
You should Math.random()
and then use Math.round()
to get 0
or 1
.
Secondly you should set matrix[y]
to an empty array otherwise code will throw error.
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)
An easier to create a matrix of any length you can use map()
. Create an array of given length and map it to a another array with same length have random values from 0
or 1
const getMatrix = len => [...Array(len)].map(x => [...Array(len)].map(b => Math.round(Math.random())));
let res = getMatrix(5);
console.log(res)
For different length and width use two parameters.
const getMatrix = (l,w) => [...Array(l)].map(x => [...Array(w)].map(b => Math.round(Math.random())));
let res = getMatrix(2,3);
console.log(res)
Upvotes: 2