Code that creates matrix with random 0 and 1 values - javascript

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])
}
}

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)

You should use Math.round(Math.random()).

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);

Related

How can I slice an array so I am left with all elements from index 1 to the second last index?

Have a look at the function below:
let myFunc = (x,y)=>{
let myArray = [];
for(let i = x; i <= y; i++) {
myArray.push(i);
}
return myArray;
}
Assuming x and y are numbers and that x will always be less than y, the above function will return an array of all numbers between x and y. How will I be able to use array slicing method to return only the numbers from index 1 to the second last index of the array?
Here is the code,
var s = [1,2,3,4,5,6];
var p = s.slice(1,s.length-1);
console.log(p);
If you don't want to include x at the beginning and y at the end, don't include them in the loop:
let myFunc = (x, y) => {
let myArray = [];
for (let i = x + 1; i < y; i++) {
myArray.push(i);
}
return myArray;
}
console.log(myFunc(5, 25))
You could use a combination of pop and shift;
pop() removes the last element of an array.
shift() removes the first element of an array.
var s = [1,2,3,4,5,6];
s.pop();
s.shift();
console.log(s);
You can give a negative number as the end argument to array.prototype.slice(), and it counts from the end. So you can use -1 to mean 2nd-to-last.
let myFunc = (x, y) => {
let myArray = [];
for (let i = x; i <= y; i++) {
myArray.push(i);
}
return myArray;
}
let anArray = myFunc(1, 10);
console.log(anArray.slice(1, -1));
myArray = ['a','b','c','d','e'];
myArray = myArray.slice(0,myArray.length-1);
console.log(myArray)
JavaScript Array Splicing

create a grid array in JavaScript

I want to setup a grid containing m * n objects. This grid got a width of m rows and n columns.
I tried this code first
let map = [][]; // Create an array that takes a x and y index
function createMap() {
for (let x = 0; x < columnCount; x++) {
for (let y = 0; y < rowCount; y++) {
addCell(x, y);
}
}
}
function addCell(x, y) {
map[x][y] = cell(); // create a new object on x and y
}
Obviously this is a wrong syntax. The initialization of map is wrong. How can I create the array that I can access a object by passing in the x and y coordinate to the array?
Let's say I want to access the object on (3|7) I want to go for map[3][7].
Is that possible?
You cant initialize a 2d array, as there are no real 2d arrays in js. However you could setup a regular array, and add arrays to it:
function createMap(columnCount, rowCount) {
const map = [];
for (let x = 0; x < columnCount; x++) {
map[x] = []; // set up inner array
for (let y = 0; y < rowCount; y++) {
addCell(map, x, y);
}
}
return map;
}
function addCell(map, x, y) {
map[x][y] = cell(); // create a new object on x and y
}
const map = createMap(10, 10);
You aren't actually that far off with your solution. You're right, though, you cannot initialize a two-dimensional array like let a = [][]. If you add just one line to your for-loops, your solution also produces a map-like structure:
In your createMap() function, you just need to initialize every field of the the array with an array, after that you can fill the fields of this array:
function createMap() {
for (let x = 0; x < 10; x++) {
map[x] = []; // initialize map[x] as an array
for (let y = 0; y < 10; y++) {
addCell(x, y);
}
}
}
And initialize map as a simple array.
Here is a working example:
let map = [];
createMap();
console.log(map);
function createMap() {
for (let x = 0; x < 5; x++) {
map[x] = [];
for (let y = 0; y < 5; y++) {
addCell(x, y);
}
}
}
function addCell(x, y) {
map[x][y] = cell(x,y); // create a new object on x and y
}
function cell(x,y) {
return (x+1)+":"+(y+1);
}
You need a single array as value and a check if one row does not exist.
function createMap(rowCount, columnCount) {
for (let x = 0; x < rowCount; x++) {
for (let y = 0; y < columnCount; y++) {
addCell(x, y);
}
}
}
function addCell(x, y) {
map[x] = map[x] || [];
map[x][y] = x + '|' + y;
}
var map = [];
createMap(4, 8);
console.log(map[3][7]);
console.log(map);
An approach by using Array.from.
function createMap(rowCount, columnCount) {
map = Array.from(
{ length: rowCount }, // take rowCount as length
(_, i) => Array.from( // fill with new array
{ length: columnCount }, // take columnCount for every row
(_, j) => [i, j].join('|') // initialize cell with some value
)
);
}
var map;
createMap(4, 8);
console.log(map[3][7]);
console.log(map);
Not sure if you are having trouble creating the grid or displaying it.
Here is yet another way to create it:
const grid = Array.from(new Array(5),(_,x)=>Array.from(new Array(5),(_,y)=>addCell(x,y)));
Here are 2 ways to show the grid:
const grid = Array.from(new Array(5),()=>Array.from(new Array(5),()=>"-"));
const rotate = grid =>
grid[0].map(
(_,y)=>grid.map(
(_,x)=>[y,x]
)
).map(
row=>row.map(([x,y])=>grid[y][x])
);
const format = grid => grid.map(x=>x.join(" ")).join("\n");
//set some values of grid
[[0,2],[1,2],[2,2],[3,2],[4,2]].forEach(
([x,y])=>grid[x][y]="X"
);
//you can map the grid to columns first, it'll look like it's rotated
// unless you generate the columns in div float lefts
console.log("map grid columns first:")
console.log(format(grid));
//you can rotate the grid to build each row and then each column like html table
console.log("map grid rows first:")
console.log(format(rotate(grid)));
var grid=[];
var grid_length=10; //mathematical length
var grid_width=10; //mathematical width
function pos(x,y){
return (y*grid_length)-grid_length-1+x-2;
}
function replaceItem(x,y,item){
grid[pos(x,y)]=item;
}
var itemsRequested=[];
function iRequest(x,y){ // get Item on grid.
itemsRequested.push(grid[pos(x,y)]); // this both adds the Object to a list and returns it
return grid[pos(x,y)];
}
This method only makes a mathematical grid, with which you can reference with the pos() function.
Then to answer your question to get the object on 3,7 you would simply say
var a=iRequest(3,7);
//currently would return undefined because there are no objects in the array.
When using this method, 1,1 is the top left corner, and pos(1,1) would return 0.
Here's a functional method that doesn't rely on any reassignment or mutation:
const lengthX = 5;
const lengthY = 2;
const map = Array.from({ length: lengthX }, (_, colIndex) => (
Array.from({ length: lengthY }, (_, rowIndex) => (
// some element to put in each, for example
{ foo: 'bar'}
))
));
console.log(map);
The colIndex and rowIndex are optional, they're not used in this snippet, but if you need to create elements based on their location in the grid, they're the variables to use.
try this:
var x = new Array(10);
for (var i = 0; i < 10; i++) {
x[i] = new Array(20);
}
x[5][12] = 3.0;

Javascript iterate objects in array only after current object

For example:
From
[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3.
x1 compares itself to x0, x2 and x3. And so on...
To
[x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3.
x1 compares itself to x2 and x3 only.
x2 only compares itself to x3.
x3 does not need to do any comparison at all.
Essentially I'm looking to traverse an array one way only, with every element behind the current element ignored.
for (var i = 0; i < boids.length; i++) {
//boids is an array containing elements "boid"
var d = distSquared(this.position.x, this.position.y, boids[i].position.x, boids[i].position.y);
//get distance between current boid and all other boids in array.
//Looking to change this to get distance between current boid and all other boids infront of this element in the array.
if (boids[i] == this) { //if the boid being compared is to its own self, skip it.
continue;
}
}
How would I go about implementing such a structure?
What you are looking for is something like this:
var a = [1,2,3,4];
for(var i=0; i<a.length; i++){
for(var j=i+1; j<a.length; j++){
console.log(i,j)
}
}
You can use Array.prototype.filter() to exclude an element or elements from an array
var arr = [1,2,3,4,5];
for (var i = 0; i < arr.length; i++) {
var curr = arr[i];
var not = arr.filter(function(_, index) {
return index != i
});
console.log(`curr:${curr}`);
not.forEach(function(el) {
console.log(`${curr} is not ${el}`)
})
}
You might do like this. Shaping up how to compare is up to you.
var arr = [1,2,3,4,5],
result = arr.map((e,i,a) => a.slice(i+1).map(n => e-n));
console.log(result);
I used Array.prototype.indexOf() to solved my issue.
var j = boids.indexOf(this);
//get index of current element i array.
if (j < boids.length) {
// if the index is lower than the overall length of the array (e.g. check traverse the array to elements infront of the current element, ignoring those behind)
//Perform calculations here
j++; //increment j
}

Storing random numbers in an array comparison

I am trying to create a function that will generate a random number and store it in an array so the first click will send the random number to the index[0] click 2 to index [1] ect. I need to be able to compare the number with the one before (index [4] with index [3].I am sure the answer is right in front of me but i cannot find a solution. Any help would be fantastic
for(i = 0;i < 12;i++) {
var random_number = Math.floor(Math.random() * 12);
var myArray = [];
myArray.push(random_number);
console.log(myArray.length);
document.getElementById("catchme").innerHTML = random_number;
}
});
http://codepen.io/kingnarwal/pen/BzjRjq?editors=1111
var myArray = [];
for(var x = 0, maxValue = 12, random_number; x < 12; x++) {
do {
random_number = Math.floor(Math.random() * maxValue );
} while(random_number == myArray[x - 1]);//Check if the number is the same value
myArray.push(random_number);
}
console.log(myArray);
This does not generate an array with random unique numbers since you're only checking the item before the current item.
To make values unique in whole array:
var myArray = [];
for(var x = 0, maxValue = 12; x < maxValue; x++) {
myArray.splice(Math.floor(Math.random() * myArray.length), 0, x);
}
console.log(myArray);
Above is a bit hackish method since it uses splice with an random index :P
Keep in mind that above method is FAR from random.
A more random method would be:
var myArray = [];
for(var x = 0, x < 12; x++) {
myArray.push(x);
}
shuffle(myArray);
console.log(myArray);
You can use an array shuffle method from here: How to randomize (shuffle) a JavaScript array?

Create a 2D Array with an X amount of one character

My goal is to make a randomly generated 2D Array in Javascript, that has an X amount of the same one character value while the rest of the values are equal to another character.
In this example, there are 10 rows and 10 columns for the 2D Array. 20 out of the possible 100 values of the Array should be equal to 'Y' (for yes) and the 80 others should be 'N' (for no). I want the 'Y's to be randomly placed all over the Array, and I absolute need exactly 20 of them to be 'Y's and the rest 'N's.
I had a less efficient way before, and I thought to try this approach, where after I define the Array, I make the first X amount of values a 'Y' and then the rest all 'N's. Then I shuffle the array, (using the shuffle from the underscore library) so that the 'Y's are all spread out randomly everywhere.
Is this an efficient way of getting what I need done? Are there any better solutions? I tried making a JSFiddle with my example, but the site appears to be down at the moment.
(I was unable to test my code yet to see if the shuffle worked correctly on my 2D array)
var rows = 10;
var cols = 10;
var elements = 20;
//Define Empty Array
var test = new Array(rows);
for (var k = 0; k < rows; k++)
{
test[k] = Array(cols);
}
var i = 1;
for (var x = 0; x < rows; x++)
{
for (var y = 0; y < cols; y++)
{
if (i <= elements)
{
test[x][y] = "Y";
}
else
{
test[x][y] = "N";
}
}
}
//Shuffle all those values so they're no longer in order
var shuffledTest = _.shuffle(test);
//Print in rows
for (var x = 0; x < rows; x++)
{
console.log(shuffledTest[x]);
}
A very simple solution is to first create an array, fill it with a number of "N"s, insert the "Y"s at random indexes, and then finally splitting it into the 2-dimensional array that you want:
var tmpArr = [], // Temporary 1-dimensional array to hold all values
arr = [], // The final 2-dimensional array
rows = 10,
cols = 10,
elements = 20; // Number of "Y"s
// 1. Fill temporary array with "N"s
for (var i = 0; i < rows * cols - elements; i += 1) {
tmpArr.push("N");
}
// 2. Insert "Y"s at random indexes in the temporary array
for (var i = 0; i < elements; i += 1) {
var index = Math.round(Math.random() * (tmpArr.length + 1));
tmpArr.splice(index, 0, "Y");
}
// 3. Split temporary array into 10 seperate arrays
// and insert them into the final array
for (var i = 0; i < rows; i += 1) {
var row = tmpArr.slice(i * cols, (i + 1) * cols);
arr.push(row);
}
JSBin to illustrate: http://jsbin.com/luyacora/1/edit
You can try this solution, it uses underscores range to create a pair of arrays to use as iterators, though their values don't matter.
Play around with the randomizer function to get an even distribution of 'y's
JSBIN: http://jsbin.com/yaletape/1/
var rows = _.range(0, 10, 0);
var columns = _.range(0, 10, 0);
function randomizer(mult){
return Math.floor((Math.random()*mult)+1);
}
var y_count = 0;
var matrix = _.map(rows, function(){
return _.map(columns, function(v, i){
var value;
var y_allowed = randomizer(3);
var current_y_count = 0;
if(y_count < 20 && current_y_count < y_allowed){
var rand = randomizer(5);
if(rand > 4){
value = 'y';
current_y_count++;
y_count++;
}
}
if(!value){
value = 'n';
}
return value;
});
});
//The above could be simplified to
var matrix = _.range(0,10,0).map(function(){
return _.range(0,10,0).map(function(){
//put the logic code from above here
});
});
Maybe shuflle a 2D array is not the best way. As #Zeb mentioned, here is some code that fill random positions with the 'Y' value. After that, the other positions are filled with 'N'.
http://plnkr.co/edit/avyKfgsgOSdAkRa1WOsk
var arr = [];
var cols = 10;
var rows = 10;
var positions = rows*cols; // 100
var YQty = 10; // only 10 'Y' are needed
// 'Y' values.
for(i = 0; i < YQty; i++)
{
do
{
x = parseInt(Math.random() * cols);
y = parseInt(Math.random() * rows);
filled = false;
if (typeof(arr[x]) == "undefined")
{
arr[x] = [];
}
if (typeof(arr[x][y]) == "undefined")
{
arr[x][y] = 'Y';
filled = true;
}
}
while (!filled);
}
// 'N' values.
for (x = 0; x < cols; x++)
{
if (typeof(arr[x]) == "undefined")
{
arr[x] = [];
}
for (y = 0; y < rows; y++)
{
if (arr[x][y] != 'Y')
{
arr[x][y] = 'N';
}
}
}
Shuffling the multidimensional array is not the best approach. Seeing as any sort is worse than linear time complexity. The easiest solution would be to create your multidimensional array and then set each index value to the char you want the 'rest' of the values to be. Then for 1 -> the number of other char value choose a random index and set that to the char.
Note: If the randomly picked spot has already been changed you need to choose a new one to make sure you have the right amount at the end.

Categories

Resources