Related
I'm trying to update every element of a 2d array only once. But unexpectedly array item gets update multiple times.
For example:
const s = "ab";
const m = [...Array(s.length).fill([...Array(s.length).fill("")])]
for(let row = 0; row < s.length; row++) {
for (let col = 0; col < s.length; col++) {
console.log(row, col)
m[row][col] += `<${row}${col}>`
}
}
console.log(m)
it should return m = [ [ '<00>', '<01>' ], [ '<10>', '<11>' ] ]
but it returns m = [ [ '<00><10>', '<01><11>' ], [ '<00><10>', '<01><11>' ] ] instead.
Can anyone explain it, please?
Update:
Here I'm looping through each item once, so there should be no
chance of updating the item twice ( two value should not concat here )
Instead of initializing array with specific length. You may just initialize empty array then push the elements. Because if you do + of 2 strings, it may just concatenate it, for example:
console.log("I "+"am");
Full working code:
const s = "ab";
let m = [];
for(let row = 0; row < s.length; row++) {
m.push([]);
for (let col = 0; col < s.length; col++) {
m[row].push(`<${row}${col}>`);
}
}
console.log(m);
The issue is that you are using <${row}${col}>, You should simple use let size=0 and use Array[i][j] = size++; in place of <${row}${col}>
you should use the following way for 2D Arrays
//Create a new 1D array
let myArray = new Array(2);
// Loop to create 2D array using 1D array
for (let i = 0; i < myArray.length; i++) {
myArray[i] = new Array(2);
}
//declare size
let size = 0;
// Loop to initialize 2D array elements.
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
myArray[i][j] = size++;
}
}
// Loop to display the elements of 2D array.
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
document.write(myArray[i][j] + " ");
}
document.write("<br>");
}
You don't even need a loop, you can use map instead.
const a = Array(2).fill(null).map(
(_, row) => Array(2).fill(null).map(
(_, col) => `<${row}${col}>`
)
);
Starting with this initial 2D array:
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
I need to create this 3D array programmatically:
var fullArray = [
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]],
[[6,7],[3,4],[1,2],[5,6],[2,3],[6,7]],
[[0,1],[4,5],[2,3],[6,7],[3,4],[0,1]],
[[1,2],[5,6],[3,4],[0,1],[4,5],[1,2]],
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]]
];
See the pattern?
On each pair, the [0] position should increment to 6 (from any starting number <= 6) and then reset to 0 and then continue incrementing. Similarly, the [1] position should increment to 7 (from any starting number <= 7) and then reset to 1 and then continue incrementing.
In this example, there are 10 2D arrays contained in the fullArray. However, I need this number to be a variable. Something like this:
var numberOf2DArraysInFullArray = 12;
Furthermore, the initial array should be flexible so that initialArray values can be rearranged like this (but with the same iteration follow-through rules stated above):
var initialArray = [[6,7],[2,3],[5,6],[4,5],[1,2],[6,7]];
Any thoughts on how to programmatically create this structure?
Stumped on how to gracefully pull this off.
Feedback greatly appreciated!
Here's a solution, I've separated the methods, and I made it so if instead of pairs it's an N size array and you want the [2] to increase up to 8 and reset to 2, if that's not needed you can simplify the of the loop for(var j = 0; j < innerArray.length; j++)
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var create3DArray = function(array, size){
var newArray = [initialArray];
for(var i = 0; i < size; i++)
{
newArray.push(getNextArrayRow(newArray[i]));
}
return newArray;
}
var getNextArrayRow = function(array){
var nextRow = [];
for(var i = 0; i < array.length; i++)
{
var innerArray = array[i];
var nextElement = [];
for(var j = 0; j < innerArray.length; j++)
{
var value = (innerArray[j] + 1) % (7 + j);
value = value === 0 ? j : value;
nextElement.push(value);
}
nextRow.push(nextElement);
}
return nextRow;
}
console.log(create3DArray(initialArray,3));
Note, the results from running the snippet are a bit difficult to read...
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var numOfArrays = 10;
// get a range array [0, 1, 2, ...]
var range = [];
for (var i = 0; i < numOfArrays; i++) {
range.push(i);
}
var result = range.reduce(function(prev, index) {
if (index == 0) {
return prev;
}
prev.push(transformArray(prev[index - 1]));
return prev;
}, [initialArray])
console.log(result);
function transformArray(arr) {
return arr.map(transformSubArray)
}
function transformSubArray(arr) {
return arr.map(function(val) {
return val == 7 ? 0 : val + 1;
})
}
Here's a pretty simple functional-ish implementation
I'm trying to build a list of Urls. The structure is like this:
http://somedomain.com/game_CATEGORY?page=NUMBER.
I have an array of game categories, ranging from action games category to word games category.
I have an array of numbers, 1 through 20.
I have pieces of the url saved as strings.
I've been trying for a day to combine them in this way:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1, // counter for page numbers
madeUrl2 = [];
for (var i = 0; i < cats.length; i++) {
madeUrl1.push(urlString1+cats[i]+urlString2);
};
for (var i = 0; i < madeUrl1.length; i++) {
madeUrl2.push(madeUrl1[i]+x);
x++;
};
console.log(madeUrl2);
This gets me partially there. But its printing out one number per category. I need each category printout to have ALL 20 numbers added, then move on to the next category.
You'd need to nest another for loop inside your second one. Something like:
for (var i = 0; i < madeUrl1.length; i++) {
for (int j = 0; j < nums.length; j++) {
madeUrl2.push(madeUrl1[i]+nums[j]);
}
};
That way you're iterating through the base URLs you prepared in madeUrl1, and then for each of those you're iterating through each number you have in the array.
If the numbers are simply sequential from 1 to 20, you don't even need the nums array:
for (var i = 0; i < madeUrl1.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl2.push(madeUrl1[i]+x);
}
};
And the whole thing could be accomplished with a single nested for loop:
for (var i = 0; i < cats.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl1.push(urlString1+cats[i]+urlString2+x);
}
};
You can use the code below:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1;
for (var i = 0; i < cats.length; i++) {
for (var j = 0; j < nums.length; j++) {
madeUrl1.push(urlString1+cats[i]+urlString2+nums[j]);
x++;
};
};
console.log(madeUrl1);
What we did here, is first nesting our loops. E.g., it will first loop through the first array, and when it arrives at it first item, in this case a category, it will run the nested loop 20 times, appending each number to the page. After done, it continues to the second category and so on.
I am iterating over a JSON array (rec'd from a webworker AJAX call)
var dataReceived = JSON.parse(xhr.responseText);//JSON verified as ok
//dataReceived.length verified
var dataProcessed = [];
for (var i = 0; i < dataReceived.length; i++) {
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
}
}
postMessage(dataProcessed);
But i get the error
dataProcessed[i] is undefined
Does Javascript not create multidimensional arrays on the fly?
Does Javascript not create multidimensional arrays on the fly?
No, you have to create it:
for (var i = 0; i < dataReceived.length; i++) {
dataProcessed[i] = []; // <============= Here
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h] = []; // <============= And here
Side note: You can make that more efficient by factoring out your repeated lookups; also, you can create and initialize the innermost array simultaneously:
var dataReceived = JSON.parse(xhr.responseText);
var dataProcessed = [];
var recEntry, procEntry;
for (var i = 0; i < dataReceived.length; i++) {
procEntry = dataProcessed[i] = [];
recEntry = dataReceived[i];
for ( var h = 0; h < recEntry.length; h++) {
procEntry[h] = [
((recEntry[h][0])*30)-30,
((recEntry[h][1])*30)-30
];
}
}
postMessage(dataProcessed);
No, javascript does not create multidimensional arrays on the fly.
You will have to look for the edge case .e.g. first iteration of the loop, and
then create an empty array.
Or you can also initialize the array using || operator
for (var i = 0; i < dataReceived.length; i++) {
dataProcessed[i] = []; // array
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h] = []; // array
dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
}
}
postMessage(dataProcessed);
So, I'm working on a javascript application that can solve any size matrix. I'm running into a SUPER weird problem, where my main array only has the value of 0 after a certain point. The input should be a data set, like this
1, 8
2, 10
3, 13
4, 17
5, 22
But I'm having trouble with it. When I run the code, the console.log prints out a pretty derpy array
[[1, 1, 1, 8],
[0, 0, 0, 0],
[0, 0, 0, 0]]
It gets even weirder. If I move the console.log to before I call the rref function, I get the same thing.
Anybody ever seen this before? Anyone know how to fix it? Thanks!
//Matrix object
var matrix = {
startingDataSet: [],
degree: 0,
M: []
}
//splits up user input into a more readable format
function getDataFromString(data) {
var points = data.split("\n");
for (var i=0; i<points.length; i++) {
points[i] = points[i].split(", ");
points[i][0] = parseInt(points[i][0]);
points[i][1] = parseInt(points[i][1]);
}
return points;
}
//finds the degree of the polynomail from the matrix object's data
function setPolynomialDegree(original) {
var data = original;
console.log(original);
//temporary data set to hold numbers in
var tempNumbers = [];
var degree = 1;
//move the original set of Y values into the temporary data set
for (var i = 0; i < data.length; i++) {
tempNumbers.push(data[i][1]);
}
//while the numbers in tempdata are not the same, execute subtraction
while (tempNumbers[0] != tempNumbers[1]) {
var newnums = []
var l = tempNumbers.length;
//find the difference for every set of numbers (0 & 1, 1 & 2, 2 & 3, etc.), and push those into the new data set
for (var i = 0; i < l - 1; i++) {
newnums.push(tempNumbers[i + 1] - tempNumbers[i]);
}
//replace old data set with new one
tempNumbers = newnums;
//increase polynomial degree by one
degree += 1;
}
return degree;
}
//add 2 arrays together
function addrows(r1, r2) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] + r2[i]);
}
return temprow;
}
//multiply array by constant
function multrow(r1, num) {
var temprow = [];
for (var i = 0; i < r1.length; i++) {
temprow.push(r1[i] * num);
}
return temprow;
}
//rref function
function rref(mtrx, deg) {
var temp1 = [];
var temp2 = [];
for (var row = 0; row < mtrx.length; row++) {
for (var j = 0; j < mtrx.length-1; j++) {
temp1 = multrow(mtrx[row], mtrx[j+1][row]);
temp2 = multrow(mtrx[j+1], mtrx[row][row]);
temp1 = multrow(temp1, -1);
mtrx[j+1] = addrows(temp1, temp2);
}
}
return mtrx;
}
//Main function that will solve the matrix
function solveFromDataSet(data) {
data = getDataFromString(data);
for (var i=0; i<data.length; i++) {
matrix['startingDataSet'].push(data[i]);
}
matrix.degree = setPolynomialDegree(matrix.startingDataSet);
matrix.M = [];
for (var i = 0; i < matrix.degree; i++) {
var row = [];
for (var j = matrix.degree; j > 0; j--) {
row.push(Math.pow(data[i][0], j - 1));
}
row.push(data[i][1]);
matrix['M'][i] = row;
}
var var_array = rref(matrix['M']);
console.log(matrix.M);
return matrix.M;
}