Created
October 5, 2021 16:52
-
-
Save mxmzb/4c24e0a6b1a43b377601c6e973b072ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findSumInArray = (arr, sum) => { | |
let needle = []; | |
let tmpSum = 0; | |
for(let i = 0; i < arr.length; i++) { | |
tmpSum = tmpSum + arr[i]; | |
needle.push(arr[i]); | |
if(sum === tmpSum) { | |
return needle; | |
} | |
for(let j = i; j < arr.length; j++) { | |
if(i === j) { | |
continue; | |
} | |
needle.push(arr[j]); | |
tmpSum = tmpSum + arr[j]; | |
// console.log({needle, i: arr[i], j: arr[j], tmpSum}); | |
if(sum === tmpSum) { | |
return needle; | |
} | |
} | |
tmpSum = 0; | |
needle = []; | |
} | |
} | |
const printSum = (arr) => { | |
return arr.map((num, i) => { | |
if(i === 0 && num > 0) { | |
return num; | |
} | |
if(i > 0 && num > 0) { | |
return `+ ${num}`; | |
} | |
if(num < 0) { | |
return `- ${num * -1}`; | |
} | |
}).join(" ") + ` = ${arr.reduce((acc, x) => acc + x, 0)}`; | |
} | |
// console.log(findSumInArray([1, 4, 20, 3, 10, 5], 33)); | |
// console.log(printSum(findSumInArray([1, 4, 20, 3, 10, 5], 33))); | |
console.log(printSum(findSumInArray([10, 2, -2, -20, 10], -10))); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment