Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active May 22, 2021 18:01
Show Gist options
  • Save rpivo/457cbb8370b3d979111b368ee8bc7155 to your computer and use it in GitHub Desktop.
Save rpivo/457cbb8370b3d979111b368ee8bc7155 to your computer and use it in GitHub Desktop.
Traverse All Subsets in an Array

Traverse All Subsets in an Array

In the below example, we create a function that's responsible for looping through an array. At each traversal, if we've reached the end of the array, we return x. Otherwise, we call the function again with i incremented, and with x added with the value of the array at index i.

function sum(arr, i = 0, x = 0) {
  return i === arr.length
    ? x
    : sum(arr, i + 1, x + arr[i]);
}

console.log(
  sum([1,2,3])
);
// 6

If we want to get the sum of all possible subsets, then we can add another call to be returned. For the example below, it would be sumOfSubsets(arr, i + 1, x). This call excludes the current item at index i of arr from being counted in the summation. When we do this recursively, we are able to traverse all subsets in this way.

function sumOfSubsets(arr, i = 0, x = 0) {
  return i === arr.length
    ? x
    : sumOfSubsets(arr, i + 1, x + arr[i]) + sumOfSubsets(arr, i + 1, x);
}

console.log(
  sumOfSubsets([1,2,3])
);
// 24

// 1 + 2 + 3 = 6
// 1 + 2     = 3
// 2 + 3     = 5
// 1 + 3     = 4
// 1         = 1
// 2         = 2
// 3         = 3
//           = 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment