Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get all sub-arrays of array arr[] with sum k
/*
References:
==============
1: HTTPS://WWW.QUORA.COM/WHAT-IS-THE-RECURSIVE-SOLUTION-FOR-FINDING-ALL-SUBSETS-OF-A-GIVEN-ARRAY
2: HTTPS://WWW.IDESERVE.CO.IN/LEARN/GENERATE-ALL-SUBSETS-OF-A-SET-RECURSION
hellow world from emacs
*/
function getSubArr (mainArr, index, sum) {
let allSubArrays = [];
let returnedSubArrays = [];
if (index === 1) {
// add fist element as sub-array
let firstKey = [];
firstKey.push(mainArr[0]);
allSubArrays.push(firstKey);
return allSubArrays;
} else {
returnedSubArrays = getSubArr(mainArr, index - 1);
for (const arr of returnedSubArrays ) {
allSubArrays.push(arr);
// deep cloing for the array
//let concatWithKey = JSON.parse(JSON.stringify(arr));
// shallow clone but will play nice with primitive data types
let concatWithKey = arr.slice();
concatWithKey.push(mainArr[index - 1]);
allSubArrays.push(concatWithKey);
}
// add key item as sub-array
let keyItem = [];
keyItem.push(mainArr[index - 1]); // make it array of single element
allSubArrays.push(keyItem);
console.log(allSubArrays); // to print output on node console
return allSubArrays;
}
}
function findSubArr (mainArr, sum) {
let allSubArr = getSubArr(mainArr, mainArr.length);
let returnArr = [];
for (let arr of allSubArr) {
let total = arr.reduce( (a, b) => a + b);
if ( total === sum ) {
returnArr.push(arr);
}
}
console.log( returnArr );
}
const arr = [1,2,3,7,8];
const k = 11;
findSubArr(arr, k);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment