Skip to content

Instantly share code, notes, and snippets.

@mxmzb
Created October 5, 2021 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxmzb/4c24e0a6b1a43b377601c6e973b072ad to your computer and use it in GitHub Desktop.
Save mxmzb/4c24e0a6b1a43b377601c6e973b072ad to your computer and use it in GitHub Desktop.
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