Create 2D array from 1D array using loop (JavaScript) - javascript

I have an array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to create a 2D array with three 1D arrays. Each NUM in the function variables is the length of each 1D array.
The result should be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
But all I get is ,,3,,,6,,,9. What am I doing wrong?
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (let i = 0; i < num.length; i++) {
for (let j = 0; j < num[i]; j++, count++) {
answer[i] = [];
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));

JavaScript doesn't have multidimensional arrays per se, what it has is arrays of arrays.
When you try to use answer[i][j] the answer[i] part of that is undefined because you haven't set it to anything yet - at that point answer is just an empty array. You need to set answer[i] = []; to set the first element of answer to be an empty array, and then you can use answer[i][j].
That will fit in your existing loop like this:
for (let i = 0; i < num.length; i++) {
answer[i] = []; // <--- add this
for (let j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}

Without testing it I believe you need to set answer[i] = [] before you loop your next array

answer[i] hasn't been created. You are trying to assign a value to something that doesn't exist. You need to create answer[i] like this:
answer[i] = new Array(num[i]);
So, the full code:
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (var i = 0; i < num.length; i++) {
answer[i] = new Array(num[i]);
for (var j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));

The problem is that answer[i] is undefined. The solution would be to add the following statement to the beginning of the first for loop:
answer[i] = [];
This should initialize answer[i] as an array, thus allowing you to set individual indices for it.

Related

How to check if the input matrix is symmetric?

The code below takes in a matrix (MAT) and transposes the matrix, calls it array. The definition of the symmetrical matrix is that it should be a square matrix and the elements in the given matrix compared to the transposed one should be the same.
The given matrix below and transposed matrix should output false if checked for symmetry.
I did create an if statement at first to check whether MAT[j][i] and array[j][i] are the same but keep getting the wrong answer. It's not properly checking all the elements together. Could someone help with that?
Thanks!
const symmetricMatrix = function (MAT) {
let array = [];
for (let i = 0; i < MAT.length; i++) {
array.push([]);
for (let j = 0; j < MAT.length; j++) {
array[i].push(MAT[j][i]);
}
}
return array;
};
console.log(
symmetricMatrix(
(MAT = [
[1, 3, 1],
[-1, 1, 4],
[2, 1, 0],
])
)
);
First you can create a copy of matrix and then transpose it and then check if it has same element at that index.
const symmetricMatrix = function (mat) {
const copy = Array.from(mat, (_) => []);
for (let i = 0; i < mat.length; i++)
for (let j = 0; j < mat.length; j++)
copy[i][j] = mat[j][i];
for (let i = 0; i < mat.length; i++)
for (let j = 0; j < mat.length; j++)
if (copy[i][j] != mat[i][j]) return false;
return true;
};
const matrix = [
[1, 3, 1],
[-1, 1, 4],
[2, 1, 0],
];
const matrix2 = [
[1, -1, 2],
[-1, 1, 1],
[2, 1, 0],
];
console.log(symmetricMatrix(matrix));
console.log(symmetricMatrix(matrix2));

I am just wondering what is going wrong with my code of adding 2 arrays in javascript

I did try this
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum = sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);
Found the right solution, However trying to understand where my code is going wrong. It says sum is not defined.
Do let me know or any ref would also do good.
Thanks Folks
Array.push does not return a new array. It modifies the given array. So basically you just need to change:
sum = sum.push(arr1[i] + arr2[j]);
To:
sum.push(arr1[i] + arr2[j]); //without the assignment
And it should work!
Assuning you want a new array with sum of each value at same index, you could take a single loop and add the values at same index.
Array#push returns the new length of the array, and has nothing to do with the pushed value.
var arr1 = [1, 2, 3, 4, 5],
arr2 = [2, 3, 4, 5, 6],
sum = [];
for (var i = 0; i < arr1.length; i++) {
sum.push(arr1[i] + arr2[i]);
}
console.log(sum);
Array.push is mutating the original array. And it will return length of updated array. so while call on 2 nd time the sum is number not array .Thats why you got error
so should not reassign sum = sum.push
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);

Cant copy elements of 2D array into another array using for loop [duplicate]

This question already has answers here:
Create copy of multi-dimensional array, not reference - JavaScript
(4 answers)
Closed 1 year ago.
What's wrong with this code?
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
Error is:
Cannot set property '0' of undefined
This is when I try to assign the value of an element of matrix1 to the new array.
for loop works for the single dimensional array.
try this
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
if(!arr[i])
arr[i] = []
arr[i][j] = matrix1[i][j];
}
}
if you want copy a 2d array without for loop try this one:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
You need to create a new sub array in the outer loop so that arr[i] is an array and not undefined
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
// push a new sub array to be populated in next loop
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
The problem is the line arr[i][j] = matrix1[i][j];, since arr[i][j] is undefined at this point.
The correct way of adding elements to an array is using the .push() function:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i].push(matrix1[i][j]);
}
}
console.log(arr);
Also note that using JSON might achieve the same task in a simpler way:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
console.log(arr)

How to transpose 2D square matrix stored as 1D array in Javascript

My question is closely related to this question but I'm looking for a solution in Javascript
How to Transpose 2D Matrix Stored as C 1D Array
Basically I have a 2D square matrix
1 2 3
4 5 6
7 8 9
Stored as follows
let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]
How can I transpose this matrix so that the elements of my source array are switched as follows?
let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9]
You could take the length for the dimension of the array and map items on a specific index for a new array.
var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
n = Math.sqrt(array.length),
transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
console.log(transposed.join(' '));
The approach in the answer you linked to works well in JavaScript too.
For a 3 x 3:
const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArray = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
newArray[3 * i + j] = anArray[3 * j + i];
}
}
console.log(newArray);
For an N x N, just replace the 3's with N.
This answer avoids division and flooring (integer division) and a decent optimizer should make the code relatively fast. You might also consider initializing the new array with
let newArray = new Array(9);
or
let newArray = new Array(N * N);
but profile the code before attempting "optimizations" such as this.
var arr1 = [];
var arr2 = [];
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
arr1.push(mat[i][j]);
}
}
for(int j=0; j<mat[i].length; j++) {
for(int i=0; i<mat.length; i++) {
arr2.push(mat[i][j]);
}
}
Set a max "width" for your matrix and insert into a new array in loops, offset by 1 for each run.
function transpose(list, width) {
if (width === void 0) {
width = 1;
}
var t = 0;
var transposed = [];
while (t < width) {
for (var index = t; index < list.length; index += width) {
transposed.push(list[index]);
}
t++;
}
return transposed;
}
//TEST
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var transposed = transpose(list, 3);
console.log(list.join());
console.log(transposed.join());

Add element to existing object with index and value

I would like to iterate through two arrays subtracting one arrays value from another and adding their specific difference values to an object. So for example I have:
var answer = [];
var boom = [1,2,3,4];
var other = [[1,2,3,4],
[2,3,4,5],
[6,7,8,9];
for(var i=0; i<other.length; i++) {
for(var e=0; e<4; e++){
answer[e] = boom[e] - other[i][e];
}
}
This give me an output of:
Object {0: -5, 1: -5, 2: -5, 3: -5}
Which is boom subtracted from the last array in other what I am looking for and I think I am very close to getting it is:
Object [{0: [ 0, 0, 0, 0]},
{1: [-1,-1,-1,-1]},
{2: [-5,-5,-5,-5]}];
You can see that it will add the results of each iteration of the second for loop to the object answer. How can I accomplish this?
for(var i=0; i<other.length; i++) {
answer[i] = [];
for(var e=0; e<4; e++){
answer[i][e] = boom[e] - other[i][e];
}
}
You need to initialize answer as an object not an as array, also you need to create a new answer array representing each set of values in other
var answer = {};
var boom = [1, 2, 3, 4];
var other = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[6, 7, 8, 9]
];
for (var i = 0; i < other.length; i++) {
var temp = answer[i] = {};
for (var e = 0; e < 4; e++) {
temp[e] = boom[e] - other[i][e];
}
}
Demo: Fiddle

Categories

Resources