Let's say I have a set number like 9 and an array that has #s [1,2,4,6,3,9]
. I was wondering what would be the best approach to loop through and see if one or more of those #s can add up to 9. My initial thought was to:
I have the first check fine but it's the other two I'm having trouble with. I know for starters that a recursive function may (or may not) be needed in addition to using reduce. Algorithms aren't my strong suit (yet) but I'm eager and more than willing to improve. Any type of guidance would be greatly appreciated.
const magicNum = 9; const arr = [10,1,2,4,6,3]; for (let i = 0, arrLength = arr.length; i < arrLength; i++) { if (arr[i] === magicNum) { console.log('Number Found!'); continue; } else if (arr[i] > magicNum) { continue; } else if (arr[i] < magicNum) { // Stuck here } }
You could take an iterative and recursive approach for finding subset sums.
function getSubsets(array, sum) { function fork(i = 0, s = 0, t = []) { if (s === sum) { result.push(t); return; } if (i === array.length) { return; } if (s + array[i] <= sum) { // shout circuit for positive numbers only fork(i + 1, s + array[i], t.concat(array[i])); } fork(i + 1, s, t); } var result = []; fork(); return result; } console.log(getSubsets([10, 1, 2, 4, 6, 3], 9));
.as-console-wrapper { max-height: 100% !important; top: 0; }
For getting only the first subset, you might exit the recursion with the first found array of values.
function getFirstSubset(array, sum) { function fork(i = 0, s = 0, t = []) { if (s === sum) { return t; } if (i === array.length) { return; } return fork(i + 1, s + array[i], t.concat(array[i])) || fork(i + 1, s, t); } return fork(); } console.log(getFirstSubset([10, 1, 2, 4, 6, 3], 9));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is more of a dynamic programming question. You can refer the following to achieve this: https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/
What you actually need is to list all the subsets of the array whose sum of digits is equal to the given magic number.
EDIT: Duplicate of find all subsets that sum to a particular value
Posting @Redu's answer from the above post:
function getSummingItems(a,t){
return a.reduce((h,n) => Object.keys(h)
.reduceRight((m,k) => +k+n <= t ? (m[+k+n] = m[+k+n] ? m[+k+n].concat(m[k].map(sa => sa.concat(n)))
: m[k].map(sa => sa.concat(n)),m)
: m, h), {0:[[]]})[t];
}
var arr = Array(20).fill().map((_,i) => i+1), // [1,2,..,20]
tgt = 9,
res = [];
console.time("test");
res = getSummingItems(arr,tgt);
console.timeEnd("test");
console.log("found",res.length,"subsequences summing to",tgt);
console.log(JSON.stringify(res));
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.