for (i = 1; i <= countPairs*2; i =2) {
num = input[i];
num2 = input[i 1];
sum = num num2;
}
Hello, I'm a JS beginner and I've run into a problem that I can't figure out how to solve. In the example I find the sum of pairs of numbers in an array. Is it possible in the same loop to check if all sums are the same? Which method do you recommend for beginners? Here is an example array: [3, 1, 1, 2, 0, 4, -2] - '3' shows how many pairs of numbers there are in the array and the result must be true because 1 1=2, 2 0=2, etc.
Tried different things but nothing worked 100%
CodePudding user response:
To check if all the sums are the same in the loop, you can store the first sum in a variable and then compare each subsequent sum to that variable. If any of the sums are different, you can set a flag variable to false and break out of the loop.
let input = [3, 1, 1, 2, 0, 4, -2];
let countPairs = input[0];
let firstSum;
let flag = true;
for (let i = 1; i <= countPairs * 2; i = 2) {
let num = input[i];
let num2 = input[i 1];
let sum = num num2;
if (i === 1) {
firstSum = sum;
} else {
if (sum !== firstSum) {
flag = false;
break;
}
}
}
if (flag) {
console.log("All sums are the same");
} else {
console.log("Not all sums are the same");
}
CodePudding user response:
I would store the first sum in a variable, then if any of the other sums is different, then all sums are not the same.
But another point, your for loop have some issues :
- you start with i = 1, so you will miss the first element of the array (array are indexed starting with 0)
- by using i <= countPairs*2 as a condition, you lack the call to the .length property on your array, plus you will end up checking undefined indexes of the array (if array.length = 5, you will try to get array[10] by the last iteration).
- using i <= countPairs.length will also overflow the array, as length is the number of elements, not considering the 0 index. So you should go with i < countPairs.length
let sumComparison = null;
let allSumsAreTheSame = true;
for (i = 0; i < countPairs.length; i =2) {
const num = input[i];
const num2 = input[i 1];
const sum = num num2;
if (sumComparison === null) {
sumComparison = sum;
}
if (sum !== sumComparison) {
allSumsAreTheSame = false;
}
}