How to create 2d array using "for" loop in Javascript? - javascript

I need to write a program that creates a 2d array in variable "numbers" in rows (5) and columns (4). The elements of the array have to be consecutive integers starting at 1 and end at 20. I have to use "for" loop.
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ],
So I came up with that:
const numbers = [];
const columns = 4;
const rows = 5;
for (let i = 0; i < rows; i++) {
numbers [i] = [];
for (let j = 0; j < columns; j++){
numbers [i][j] = j + 1;
}
}
console.log(numbers);
But the result of this is five identical rows, like this:
[ 1, 2, 3, 4 ],
[ 1, 2, 3, 4 ],
[ 1, 2, 3, 4 ],
[ 1, 2, 3, 4 ],
[ 1, 2, 3, 4 ]
Do you have any idea how to fix it? How to make second row starting from 5?

Here is some updated code. You need to add i*columns to every value
const numbers = [];
const columns = 4;
const rows = 5;
for (let i = 0; i < rows; i++) {
numbers[i] = [];
for (let j = 0; j < columns; j++){
numbers[i][j] = j + 1 + (i*columns);
}
}
console.log(numbers);

Looks like in the second loop, you should do numbers [i][j] = j * i; instead

Every time the outer for loop starts a new iteration, j is reset back to 0, which is why you keep getting rows starting with 1.
To fix this, you could declare a variable outside of the for loops that tracks the current number, and use that instead of j like so:
const numbers = [];
const columns = 4;
const rows = 5;
let currNum = 0;
for (let i = 0; i < rows; i++) {
numbers [i] = [];
for (let j = 0; j < columns; j++){
currNum++;
numbers [i][j] = currNum;
}
}
console.log(numbers);

Related

Print alternatively one element from the last and one from the first (JavaScript)

Print alternatively one element from the last and one from the first (JavaScript)
input
1, 3, 6, 3, 2, 8
output:
8, 1, 2, 3, 3, 6
You can use the below approach
var array = [];
var size = prompt('Enter Array Size'); //Maximum Array size
for(var i=0; i<size; i++) {
//Taking Input from user
array[i] = prompt('Enter Element ' + (i+1));
}
//Print the array in the console.
console.log("Array Input: "+array.join(','));
let output = [];
let l = array.length - 1;
for (let i = 0; i <= l; i++, l--) {
if (i>=array.length/2) {
console.log(array[i]);
break;
}
output.push(array[l]);
output.push(array[i]);
}
console.log("Resultant Array: "+output.join(','));
Anyways you can try the below logic.
const input = [1, 3, 6, 3, 2, 8];
let output = [];
for (var i = 0; i < input.length / 2; i++) {
output.push(input[i]);
output.push(input[input.length - (i + 1)]);
}

Convert 1D array into 2D array JavaScript

Hi I have this example where I want my 1D array to be a 2D array 4x3
var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);
for (t = 0; t < 4; t++) {
array2[t] = new Array(3);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
array2[i][j] = array1[i];
array2[i][j] = array1[j];
}
positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}
console.log(array2);
My solution is only giving me the first numbers of the array1. Any idea?
i and j are indexes into the new 2D array that only run up to 0 to 3 and 0 to 2, which is why you are seeing the beginning values over and over. You need a way to index array1 that goes from 0 to 11.
It looks like you are on the right track with "positionarray1" and "position", though you need to move where you are incrementing it. You need to use that value when indexing array1 rather than i and j:
array2[i][j] = array1[positionarray1];
array2[i][j] = array1[positionarray1];
positionarray1++;
If you rename i to row and j to col, it makes is easier to see what is going on. Also, avoid magic numbers. I am seeing 3 and 4 all over the place. These can be replaced with parameter references. All you need to do it wrap your logic within a reusable function (as seen in the reshape function below).
The main algorithm is:
result[row][col] = arr[row * cols + col];
There is no need to track position, because it can be calculated from the current row and column.
const reshape = (arr, rows, cols) => {
const result = new Array(rows);
for (let row = 0; row < rows; row++) {
result[row] = new Array(cols);
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
result[row][col] = arr[row * cols + col];
}
}
return result;
};
const array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
const array2 = reshape(array1, 4, 3);
console.log(JSON.stringify(array2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);
for (t = 0; t < 4; t++) {
array2[t] = new Array(3);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
array2[i][j] = array1[i*3+j]; //here was the error
}
positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}
console.log(array2);
I just solved it thanks for your comments. I actually used one apportation, but it was 3 instead of 2.
solution with 1 loop for efficiency :
const arr1D = new Array(19).fill(undefined).map((_, i) => i);
const arr2D = [];
const cols = 3;
for (let i = 0, len = arr1D.length; i < len; ++i) {
const col = i % cols;
const row = Math.floor(i / cols);
if (!arr2D[row]) arr2D[row] = []; // create an array if not exist
arr2D[row][col] = arr1D[i];
}
console.log({ arr1D, arr2D });

divisibleByThreePairSum, I get pair repeats

i'm just beginning to learn javascript and this is my first question on stackoverflow, so feel free to criticize me if i'm approaching this the wrong way.
var divisibleByThreePairSum = function(array) {
var pairs = [];
for (var i = 0; i < array.length; i++) {
for (var j = i++; j < array.length; j++) {
var sum = array[i] + array[j];
if (sum % 3 === 0) {
pairs.push([i, j]);
}
}
}
return pairs;
}
console.log(divisibleByThreePairSum([3,1,0,2,1,3,2,0]));
This gives me the answer;
[ [ 1, 3 ], [ 1, 6 ], [ 3, 4 ], [ 5, 5 ], [ 5, 7 ], [ 7, 7 ] ]
[Finished in 0.2s]
For the second "for" loop, I formatted it like so, (j = i++) as to avoid repeats like [1, 3], [3, 1], but I can't seem to get rid of getting pairs like [5, 5], and [7, 7]. Is there any possible ways to format the code differently so that this doesn't happen? Again, I apologize if this was asked improperly; i'll definitely be using this site more often so please let me know if i'm doing anything wrong "question format" wise, Thanks!
Issue is j = i++. This will assign value of i to j and then increment value of i. This will also result in skipping of alternate values of i as it is incremented twice.
for(var i = 0; i< 5; i++){
for(var j = i++; j< 5; j++){
console.log(i,j)
}
}
You should rather use j=i+1. This will sent next value and will not increment value of i
var divisibleByThreePairSum = function(array) {
var pairs = [];
for (var i = 0; i < array.length; i++) {
for (var j = i+1; j < array.length; j++) {
var sum = array[i] + array[j];
if (sum % 3 === 0) {
pairs.push([i, j]);
}
}
}
return pairs;
}
console.log(divisibleByThreePairSum([3, 1, 0, 2, 1, 3, 2, 0]));

Javascript Array grouping category

I have a problem with grouping an array of numeric value:
I have values in an array like this
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
that are then sorted into ascending numerical order
var sortedNumb = [1,1,2,3,4,4,5,5,6,6,7,7,8,10,11,12,15,15,18,20];
Now I want to create a group of numbers like
1-4 , 5-8 , 9-12 , 13-16 , 17-20
Is it possible to create groups dynamically, like that?
// important code
var numberToGroupOn = 4;
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
var srt = numb.slice(0).sort(function(a, b) { return a - b; });
var groupCount = Math.ceil(srt[srt.length-1] / numberToGroupOn);
var grps = {};
for(var i = 1; i <= groupCount; i++)
{
grps[((i*numberToGroupOn)-(numberToGroupOn-1)).toString() + '-' + (i*numberToGroupOn).toString()] =
srt.filter(function(a) {return (a <= i*numberToGroupOn) && (a >= (i*numberToGroupOn)-(numberToGroupOn-1))});
}
// unimportant code to see output in SO snippet
var output = '';
for(var key in grps)
{
output += key + ': ' + grps[key]+'<br>';
}
document.write(output);
This figures out the number of groups and then builds a dictionary of the groups using Array.prototype.filter.
It only works with positive numbers.
Assuming that 1-4, 5-8, 9-12, 13-16, 17-20 grouping means that you want 5 groups, the first one (1-4) containing all the numbers within the [1, 4] interval; the second one (5-8) containing all the numbers within the [5, 8] interval, and so on.
// numbers and intervals must be in ascending order
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
// 1-4 , 5-8 , 9-12 , 13-16 , 17-20
var intervals = [4, 8, 12, 16, 20];
numb.sort(function (a, b) {
return a - b;
});
var groups = [];
var j = 0;
for (var i = 0; i < intervals.length; i++) {
var group = [];
while (numb[j] <= intervals[i]) {
group.push(numb[j]);
j++;
}
groups.push(group);
}
console.log(groups);
The output:
[ [ 1, 1, 2, 3, 4, 4 ],
[ 5, 5, 6, 6, 7, 7, 8 ],
[ 10, 11, 12 ],
[ 15, 15 ],
[ 18, 20 ] ]
EDIT: After reading the comment about calculating the intervals based on the max number in the array.
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
numb.sort(function (a, b) {
return a - b;
});
var max = numb[numb.length - 1];
// Five groups based on the max value of the array
var increment = max / 5;
var groups = [];
var j = 0;
for (var i = increment; i <= max; i += increment) {
var group = [];
while (numb[j] <= i) {
group.push(numb[j]);
j++;
}
groups.push(group);
}
console.log(groups);
Output:
[ [ 1, 1, 2, 3, 4, 4 ],
[ 5, 5, 6, 6, 7, 7, 8 ],
[ 10, 11, 12 ],
[ 15, 15 ],
[ 18, 20 ] ]
Code : Assuming sortedNumb is not empty :)
var sortedNumb = [1,1,2,3,4,4,5,5,6,6,7,7,8,10,11,12,15,15,18,20];
var groups = [[sortedNumb[0]]];
var lastfirstValueInArray = sortedNumb[0];
var i = 1;
var j = 0;
while (i < sortedNumb.length)
{
if (sortedNumb[i] >= lastfirstValueInArray+4 || (sortedNumb[i]%4 == 1 && sortedNumb[i] != lastfirstValueInArray))
{
j++;
lastfirstValueInArray = 1+j*4;
groups[j] = [];
}
groups[j][groups[j].length] = sortedNumb[i];
i++;
}
console.log(groups);
Output :
[Array[6], Array[7], Array[3], Array[2], Array[2]]
Edit :
You seemed to want a range of group of 4, if you want N, just create a function taking it as parameter, and replace all 4 by N in code =)

JS Matrix Multiplication Issue

I'm having trouble with matrix multiplication code in JavaScript. If I run the function below with the following two matrices:
var m1 = [ [ 1, 0, 0 ],
[ 0, 1, 0 ],
[ 1, 1, 0 ],
[ 0, 0, 1 ],
[ 1, 0, 1 ],
[ 0, 1, 1 ],
[ 1, 1, 1 ] ];
var m2 = [ [ '0', '1', '1', '0', '0', '1', '1' ] ];
var matrixMult = function (m1, m2) {
console.log(m1);
console.log(m2);
console.log("m1 length: %d, m2[0].length: %d", m1.length, m2[0].length);
if (m1.length != m2[0].length) {
console.error("Incompatible matrix dimensions for multiplication.");
return false;
}
var result = [];
for (var i = 0; i < m1[0].length; i++) {
result[i] = [];
for (var j = 0; j < m2.length; j++) {
var sum = 0;
for (var k = 0; k < m1.length; k++) {
sum += m1[i][k] * m2[k][j];
}
result[i][j] = sum;
}
}
return result;
}
I get this error:
/path/to/file.js:58
sum += m1[i][k] * m2[k][j];
^
TypeError: Cannot read property '0' of undefined
at matrixMult (...)
What's going wrong? Could the issue be that m2.length is only 1?
There is only a m2[0], but your inner for loop runs from 0 to m1.length, which is bigger than 0. So when it tries accessing m2[1] it throws the error.
Also by following definition of matrix multiplication
Multiplication of two matrices is defined only if the number of columns of the left matrix is the same as the number of rows of the right matrix.
(Source: Wikipedia)
you cannot multiply your sample matrixes, because m1 has 3 columns, but m2 has only one row.
EDIT
Now that I understood your question correctly, I wrote a little function that might help you out:
function multiplyMatrix(m1, m2) {
var result = [];
for(var j = 0; j < m2.length; j++) {
result[j] = [];
for(var k = 0; k < m1[0].length; k++) {
var sum = 0;
for(var i = 0; i < m1.length; i++) {
sum += m1[i][k] * m2[j][i];
}
result[j].push(sum);
}
}
return result;
}
multiplyMatrix(m1, m2);
// => [ [2, 4, 2] ]

Categories