i used a console.log for a 3d array and this is its contents
for the second its contents are clear
for(let mmm = 0; mmm < NumOfPatterns;mmm++)
{
for(let i = 0; i < 36; i++)
{
for(let j = 0; j < 36; j++)
{
patterns[mmm][i][j] = 0;
console.log(patterns[mmm][i][j]);
}
}
}
I use this function just to define every value to 0
I think you should check if the arrays exist:
const NumOfPatterns = 10
const DEFAULT_ARR_LENGTH = 36
let arr3d = []
// checking if the referenced elements exist
// if not, create them on the first iteration
for (let mmm = 0; mmm < NumOfPatterns; mmm++) {
if (typeof arr3d[mmm] === "undefined") arr3d[mmm] = []
for (let i = 0; i < DEFAULT_ARR_LENGTH; i++) {
if (typeof arr3d[mmm][i] === "undefined") arr3d[mmm][i] = []
for (let j = 0; j < DEFAULT_ARR_LENGTH; j++) {
arr3d[mmm][i].push(0)
}
}
}
console.log(arr3d)
Related
I have a json array object which is getting constructed using two different array objects.
But after looping I'm getting the value of the last looped value for every array.
But for the serial number element I'm getting the value of the last iterated value. Am I missing something?
for (z = 0; z < postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter.length; z++) {
for (i = 0; i < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches.length; i++) {
for (j = 0; j < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters.length; j++) {
for (k = 0; k < ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails.length; k++) {
if (ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails[k].Key === "meter_serial_number") {
var serialNumber1 = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches[i].Meters[j].MeterDetails[k].Value;
}
}
electricityMeterObject = {
"Check": true,
"serialNumber": serialNumber1
}
electricityArray.push(electricityMeterObject);
}
}
}
This is easier to debug
const meter = postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter,
matches = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches;
for (let z = 0; z < meter.length; z++) {
for (let i = 0; i < matches.length; i++) {
for (let j = 0; j < matches.Meters.length; j++) {
for (let k = 0; k < matches[i].Meters[j].MeterDetails.length; k++) {
if (matches[i].Meters[j].MeterDetails[k].Key === "meter_serial_number") {
electricityArray.push({
"Check": true,
"serialNumber": matches[i].Meters[j].MeterDetails[k].Value
});
}
}
}
}
}
Or
const meter = postAdvancedAddressCheckRequest.addressCheck.energyQuoteAddress.electricityMeter,
matches = ecoesGetTechnicalDetailsByMpanResponse.Results[0].UtilityMatches;
meters.forEach(meter => {
matches.forEach(match => {
match.Meters.forEach(meter => {
meter.MeterDetails.forEach(detail => {
if(detail.Key === "meter_serial_number") {
electricityArray.push({
"Check": true,
"serialNumber": matches[i].Meters[j].MeterDetails[k].Value
});
}
})
})
})
})
Here is my code sans input
// Check if three addends equal sum and return the product if so
let result;
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
result = first * second * third;
return (first * second * third);
}
};
// find three numbers in list that add up to specific number
function testResult(list,sum) {
let firstAddend;
let secondAddend;
let thirdAddend;
for (let i = 0; i < list.length; i++) {
firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
};
What I want is testResult() to return the result from addNumbers() when it returns the product. I want to get rid of let result; and result = ... in addNumbers(). I've been confused about scope but I think I'm starting to understand. Does each for loop contain the scope of the previous? If anyone is interested this is from Advent of Code Day 1. I am not certain if having the data is necessary here. If it is let me know and I will edit accordingly.
Does each for loop contain the scope of the previous?
Yes, it does. Whenever you create a sub-scope, all the variables in the previous scope are available. So, you don't actually have to declare firstAddend and secondAddend and thirdAddend ahead of time:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
}
Next, the return means that when you call the function, it takes on the value that you return. So, you don't need a global result variable, as you can just utilize the return value. However, you should move the if statement out of the addNumbers function and into the testResult function, as you need to know when to return, not just what to return. In fact, the addNumbers function is simply enough to where it should just go directly into testResult:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
if (firstAddend + secondAddend + thirdAddend === sum) {
return firstAddend * secondAddend * thirdAddend;
}
}
}
}
}
For practice, if you want the function, you could do something like the following:
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
return (first * second * third);
} else {
return null; // return some value so the calling function knows that no sum was found
}
}
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
let result = addNumbers(firstAddend, secondAddend, thirdAddend, sum);
if (result !== null) {
return result;
}
}
}
}
}
There is a cycle with the condition how can it be optimized so that the search is faster?
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
for (var k = 0; k < work.length; k++) {
if (db.rows[i].LOGIN === user.rows[j].login && work[k].name === db.rows[i].NAME) {
}
}
}
}
This is typically something that you would expect to see executed on the database.
That being said, you can split up the condition, so that you don't need to perform the second nested loop for every row:
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
if (db.rows[i].LOGIN === user.rows[j].login) {
for (var k = 0; k < work.length; k++) {
if (work[k].name === db.rows[i].NAME) {
}
}
}
}
}
You could take two Maps for the user logins and work names.
var userLogins = new Map(user.rows.map(o => [o.login, o])),
workNames = new Map(o => [o.name, o]),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
If you need just the simple check with using the objects of user.rows or work, you could take a Set instead.
var userLogins = new Set(user.rows.map(({ login } => login)),
workNames = new Set(({ name }) => name),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
When I run the third line alone and log test2darr it returns a 2D array filled with 6's in a 3x3 matrix
But when I run the fourth line and log test2darr again, it returns:
[4, 5, 4]
[5, 6, 5]
[4, 5, 4]
(as well as for secondtest)
Though it should return the same array of 6's for test2darr and on assign the 2d array to secondtest
const n = 3;
const filler = new Array(n * n);
const test2darr = fill2DarrFromArr(filler.fill(6));
const secondtest = pileReduce(test2darr);
Here is my code for fill2DarrFromArr and pileReduce:
function pileReduce(_cells) {
_cells = fillEmpty(_cells);
for (let j = 0; j < _cells.length; j++) { //The Algorithm itself is not important
for (let i = 0; i < _cells.length; i++) { // But there might be some assignment problem that I missed
if (_cells[j][i] >= 4) {
_cells[j][i] = _cells[j][i] - 4;
if (j !== _cells.length - 1) _cells[j + 1][i]++;
if (j !== 0) _cells[j - 1][i]++;
if (i !== _cells.length - 1) _cells[j][i + 1]++;
if (i !== 0) _cells[j][i - 1]++;
}
}
}
return _cells;
}
function fill2DarrFromArr(_arr) {
let sideLength = Math.sqrt(_arr.length);
let out = create2DArr(sideLength, sideLength);
for (let j = 0; j < sideLength; j++) {
for (let i = 0; i < sideLength; i++) {
out[j][i] = _arr[j * sideLength + i];
}
}
return out;
}
function create2DArr(_n, _m) {
let _arr = new Array(_n);
for (let j = 0; j < _m; j++) {
_arr[j] = new Array(_m);
}
return _arr;
}
function fillEmpty(_arr) {
for (let j = 0; j < _arr.length; j++) {
for (let i = 0; i < _arr.length; i++) {
if (!_arr[j][i]) _arr[j][i] = 0;
}
}
return _arr;
}
Passing an array into a function doesn't create a copy of that array. Your functions are modifying the contents of the passed arrays, therefore they have side effects.
This is a bad coded solution to a problem in "advent of code": link to problem
I don't know the reason because my code is not working properly, I had an error related to regular expressions cause I didn't reset the pointer of the regexp object, now that error is fixed I think, but something is escaping to my knowledge in what I've done bad.
The problem is that the solution that my code displays is not correct, you can submit a solution on the link I've provided and get feedback of your solutions.
Correct solution: 543903
Given solution: 418954
// day 6 of advent of code
var input = "removed, take from problem";
function processInput(input, matrix) {
var linesOfInput = input.split("\n");
var matches;
var turnOnRE = /turn on (\d+),(\d+).*?(\d+),(\d+)/g;
var turnOffRE = /turn off (\d+),(\d+).*?(\d+),(\d+)/g;
var toggleRE = /toggle (\d+),(\d+).*?(\d+),(\d+)/g;
// regular expression objects lastIndex property must be 'reseted' in order to work well
for (var i = 0 ; i < linesOfInput.length; i++) {
turnOnRE.lastIndex = 0;
turnOffRE.lastIndex = 0;
toggleRE.lastIndex = 0;
matches = turnOnRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], true);
continue;
}
matches = turnOffRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], false);
continue;
}
matches = toggleRE.exec(linesOfInput[i]);
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4]);
}
}
function manipulateLights(matrix, startI, startJ, endI, endJ, newValue) {
if (newValue == undefined) { // toogle
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = !matrix[i][j];
}
}
console.log(startI, startJ, endI, endJ, newValue);
} else {
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = newValue;
}
}
console.log(startI, startJ, endI, endJ, newValue);
}
console.log(countTurnedOnLights(matrix));
}
function countTurnedOnLights(matrix) {
var turnedOn = 0;
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
if (matrix[i][j] == true) {
turnedOn++;
}
}
}
return turnedOn;
}
var matrixHeigth = 1000;
var matrixWidth = 1000;
// define a bidimensional array, is almost like in C++
var lightMatrix = new Array(matrixWidth);
for (var i = 0 ; i < matrixWidth; i++) {
lightMatrix[i] = new Array(matrixHeigth);
}
// turn off all lights
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
lightMatrix[i][j] = false;
}
}
processInput(input, lightMatrix);
console.log(countTurnedOnLights(lightMatrix));
OK I figured out the error - your regular expression matches are being treated as strings when you first create your for loops.
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
When you hit a combo like 756,53 through 923,339, it thinks 53 > 339 and it exits the loop immediately. Either wrap each "start" variable with Number() in your for loops, or do so when passing the parameters.