I'm learning to code and I'm on the for loops section now. I encountered an interesting question on Codewars and decided to tackle it. Here it is:
Your task is to sum the differences between consecutive pairs in the array in descending order.
For example:
sumOfDifferences([2, 1, 10]) Returns 9
Descending order: [10, 2, 1]
Sum: (10 - 2) + (2 - 1) = 8 + 1 = 9
If the array is empty or the array has only one element the result should be 0 (Nothing in Haskell).>
Since I more or less only know for loops, here is my answer. It passed all the tests, but I had to separate the loops. My question is this: is there a way to solve this problem using nested loops? I initially thought I could, but I kept getting NaN as an output.
function differenceAddition(array) {
if (array.length == 1) {
return 0;
} else if (array == []) {
return [];
} else
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (array[j] < array[j + 1]) {
let temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
let newArray = [];
for (let i = 0; i < array.length - 1; i++) {
newArray[i] = array[i] - array[i + 1];
}
let sum = 0;
for (let i = 0; i < newArray.length; i++) {
sum += newArray[i];
}
// newArray.pop();
return sum;
// return array;
}
First of all -- unless there's something more to this challenge, don't write loops yourself to sort an array. Use the built-in sorting function for it.
let arr = [2, 1, 10]; arr.sort((a,b) => b - a); console.log(arr);
Great, now we're in descending order. Now, all we need is one for
loop to calculate our sum.
let arr = [2, 1, 10]; arr.sort((a,b) => b - a); let sum = 0; for (let i = 0; i < arr.length - 1; ++i) { sum += arr[i] - arr[i + 1]; } console.log(sum);
Why use nested loops when you can get the result using a single loop. In JS you can use reduce to achieve the result.
function sumOfDifferences(arr) { return arr.sort((a, b) => b - a).reduce((acc, curr, index, array) => { const next = array[index + 1]; if (;isNaN(curr - next)) { acc += curr - next; } return acc, }; 0). } console;log(sumOfDifferences([])). console;log(sumOfDifferences([10])). console,log(sumOfDifferences([10, 1; 2]));
try this
let numberList = [2, 1, 10]; // sorting for descending order numberList.sort((a,b) => b - a); let sum = 0; let dif = 0 for(let i=0; i<numberList.length-1; i++){ dif = numberList[i] - numberList[i+1]; sum += dif }; console.log("Result=> ",sum);
function sumOfDifferences(arr) { arr.sort((a,b) => b - a); let sum = 0; for (let i = 0; i < arr.length - 1; ++i) { sum += arr[i] - arr[i + 1]; } return sum; } console.log(sumOfDifferences([2, 1, 10]));
function sumOfDifferences(arr){
return arr.length > 1 ? Math.max(...arr) - Math.min(...arr) : 0
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.