Convert an array to a 2D array (Square matrix) in javascript - javascript

I have got a little function in javascript and I want to split an array A into a 2d array.
I will be used for square matrices. Obviously,I want it to be 2x2 if a square matrix of 2x2 is in the input and so on for 3x3 and. But I'm stuck after having read a first row.So my arr rows are repeated. Does anyone have any ideas about how I can get the next rows read properly.So,for instance,lets say I do have an array
A = [2,1,4,5,1,2,3,1,9]
Then I want my array arr to look like this:
arr = [[2,1,4],[5,1,2],[3,1,9]]
This will later be used for calculation a determinant of a matrix.
function create2Darray(clname) {
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < rows; j++) {
arr[i][j] = A[j].value;
}
}
}

You are assigning always the same value. It should be something like:
arr[i][j] = A[i*rows+j].value;
EDIT: Here's a complete function without the DOM manipulation (that is, A is a simple array of integers):
function create2Darray(A) {
var arr = [];
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = [];
for (var j = 0; j < rows; j++) {
arr[i][j] = A[i * rows + j];
}
}
return arr;
}
console.log(create2Darray([1, 2, 3, 4, 5, 6, 7, 8, 9]))

Related

Create nested arrays that mimic a grid using for loops

I am trying to make nested arrays that mimic a grid using for loops. I want it to look like this:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
I have been able to create one line of the array like so
[0, 0, 0]
using
var num = 3;
var arr = [];
for (var j = 0; j < num; j++) {
arr[j] = 0;
}
console.log(arr);
I stuck with how to implement nesting the second for loop around the first. My thought would be to push the finished output of the inner loop to the i index of of the outer loop. So something like
var num = 3;
var arr = [];
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
arr[j] = 0;
}
// some command here to push the completed output of the inner output to i index of the outer loop
}
console.log(arr);
I am on the right track with this? If not, where do I need to shift my thinking here? I haven’t been able to get a solution that produces the desired outcome yet.
You just needed to initialize the subarray for each set, then utilize both counters to place your '0'
var num = 3;
var arr = [];
for (let i = 0; i < num; i++) {
arr[i] = [];
for (let j = 0; j < num; j++) {
arr[i][j] = 0;
}
}
console.log(arr);

js how to make 2d array matrix with for loop and continue counting numbers on next row

I'm trying to make my 2d matrix to have numbers which continue on the new row
var myMatrix = [];
var row = 5;
var colom = 3;
for (var i = 0; i < rows; i++) {
var toto = 1;
myMatrix[i] = [i];
for (var j = 0; j < colom; j++) {
myMatrix[i][j] = [i + j];
}
}
console.log(myMatrix);
I'm trying to make it print numbers like this:
123
456
789 and etc...
but without success:/
can someone help and also give a video or site with examples where i can learn more about that kind of stuff?
First, a look at what your code is doing:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [i];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = [i+j];
}
}
console.log(myMatrix);
You have a typo in your row/rows variable name. Ignoring that though...
Your myMatrix[i] line is creating an array at i, which is then being set to an array with a value of i. Just this creates a wonky mash-up , where each "row" gets an array with it's row number as the first value, something like this:
[[0], [1], [2], [3], [4]]
Your inner loop then adds a value to that array at the place and adds i+j together, but puts that inside of an array, which isn't what you want, so you get something like this:
[
[[0], [1], [2]], // i = 0
[[1], [2], [3]], // i = 1
[[2], [3], [4]], // i = 2
// ... etc
]
Also note that you are replacing that first [i] anyways, so don't set it like that, just make it an empty array [].
What you want is something like this:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j;
}
}
console.log(myMatrix);
There were three changes to your code:
Make the [i] and []. It doesn't hurt anything, but [i] also doesn't make sense.
Take the i+j part out of the array, you just want a value there.
When you add i, multiply it by columns so it doesn't reset every time: (i*columns)+j
This will give you a nice output, starting with 0. If you want it start at 1, just add one to your value:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j+1;
}
}
console.log(myMatrix);
Use i * columns + j ... and I have to add up to 30 chars for padding

Javascript Diagonal Matrix

I need to do a simple diagonal matrix in JS, which should look like this one:
[
[4, 7, 9],
[2, 5, 8],
[1, 3, 6]
]
My idea is to use a 2-d array and two loops, but the result I get is an empty array.You'll see below what my code looks like, but obviously I have a problem with the values.
function fillMatrix(n) {
var matrix = [];
var rows = 0;
var cols = 0;
var startCount = 1;
for (var i = (n - 1); i >= 0; i--) {
rows = i;
cols = 0;
matrix[rows] = [];
while (rows < n && cols < n) {
matrix[rows++][cols++] = startCount++;
}
for (var j = 0; j < n; j++) {
rows = j;
cols = 0;
matrix[rows] = [];
while (rows < n && cols < n) {
matrix[cols++][cols++] = startCount++;
}
}
}
return matrix;
}
n = +prompt();
console.log(fillMatrix(n));
The logic for creating a diagonal matrix can be greatly simplified if one looks at the patterns between rows. (I won't go through all of the math here, but feel free to ask me questions in the comments about any specific sections you find confusing.)
Take, for example, the 4x4 diagonal matrix:
Successive differences between elements in a row form the pattern below:
I might still work on shortening the method below, but right now it works and is fairly concise.
Demo:
function diagonalMatrix (n) {
var matrix = [], row
for (var i = n; i > 0; i--) {
var x = i*(i-1)/2 + 1, dx = i
matrix.push(row = [])
for (var j = n; j > 0; j--) {
row.push(x)
x += (i < j ? ++dx : dx--)
}
}
return matrix
}
var matrix = diagonalMatrix(+prompt('Diagonal Matrix Order:'))
console.log(beautify(matrix))
console.log(matrix)
// For visualization purposes
function beautify (matrix) {
return matrix.map(function (e) {
return e.join('\t')
}).join('\n\n\n\n')
}
.as-console-wrapper { min-height: 100vh; }

Javascript Array function has bug I cannot see

I am writing a function which should create a 2 dimensional array pre-populated with zeros. My output looks correct, but apparently there is a bug in it that I am not seeing. Does anybody know what it is? I don't see it.
function createMatrix(size) {
var defValue = 0;
var row = [];
var matrix = [];
for (var i = 0; i < size; i++) {
row.push(defValue);
}
for (var i = 0; i < size; i++) {
matrix.push(row);
}
return matrix;
}
You're pushing the same row into your array matrix every time. These all point to the same array, since they are passed by reference.
You should make a new array for each row instead:
function createMatrix(size){
var defValue = 0;
var matrix = [];
for (var i = 0; i < size; i++) {
var row = [];
for (var j = 0; j < size; j++) {
row.push(defValue);
}
matrix.push(row);
}
return matrix;
}
The problem lies in the second loop;
If you stop and trace your code, you can see that you are only creating one "row" array whereas you most likely want to make size amount of rows.
Your code should probably look like this
var matrix = [];
for(var i = 0; i < size; i++) {
//temp row to append to array
var row = [];
//fill row array with 0s
for (var j = 0; j < size; j++) {
row.push(0);
}
//append row to the matrix
matrix.push(row);
}
return matrix
This way you are pushing a completed row at the end of each iteration.

Efficient way to turn a string to a 2d array in Javascript

I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

Categories