-2

How would you get all possible combinations of an array of numerical values similar to python itertools without using itertools npm package in this same order?

This is a python implementation.

from itertools import combinations

input = [0,1,2,3]

output = sum([list(map(list, combinations(input, i))) for i in range(len(input) + 1)], [])
>>> output
[[],
 [0],
 [1],
 [2],
 [3],
 [0, 1],
 [0, 2],
 [0, 3],
 [1, 2],
 [1, 3],
 [2, 3],
 [0, 1, 2],
 [0, 1, 3],
 [0, 2, 3],
 [1, 2, 3],
 [0, 1, 2, 3]]
karel
  • 5,489
  • 46
  • 45
  • 50
Emptybox
  • 121
  • 1
  • 10
  • 1
    Does this answer your question? [How to find all subsets of a set in JavaScript?](https://stackoverflow.com/questions/42773836/how-to-find-all-subsets-of-a-set-in-javascript) – CRice May 05 '20 at 14:52
  • That question returns subset of combinations, but does not address the order parameter. It does not answer this question. When running a test using the prescribed solution it returns unordered list of combinations. – Emptybox May 05 '20 at 15:15
  • The top comment on the accepted answer there reads: If you reverse `[value,...set]` to be `[...set,value]` then it also preserves order. If you take that answer and apply the patch described in the comment, then order is preserved and you will get exactly the output you gave in your example. – CRice May 05 '20 at 15:19
  • I integrated the top comment and the return does match the requested output. It only maintains order within each subset, but does not match the requriement. ``` const getAllSubsets = theArray => theArray.reduce((subsets, value) => subsets.concat(subsets.map(set => [...set,value])),[[]]); output [[] [0] [1] [0, 1] [2] [0, 2] [1, 2] [0, 1, 2] [3] [0, 3] [1, 3] [0, 1, 3] [2, 3] [0, 2, 3] [1, 2, 3] [0, 1, 2, 3]] ``` – Emptybox May 05 '20 at 15:27
  • 1
    Ah, I see yes the order is different, I apologize, my earlier comment was mistaken. You could certainly sort the result array after the fact: `getAllSubsets([0, 1, 2, 3]).sort((a, b) => a.length - b.length || String(a).localeCompare(String(b)))` – CRice May 05 '20 at 16:00
  • @CRice Thank you for your comment/response. That sorting method along with the previous alteration returns the correct output. – Emptybox May 05 '20 at 20:31

1 Answers1

0

This function will return similar results as stated in the question and sorts the subsets and the complete array.

getAllSubsets function from How to find all subsets of a set in JavaScript?

function getUniqueSortedCombinations(inputArray){
  
  const getAllSubsets = theArray => theArray.reduce((subsets, value) => subsets.concat(subsets.map(set => [...set,value])),[[]]);
      
  let subset = getAllSubsets(inputArray)
      
  subset.sort((a, b) => a.length - b.length || String(a).localeCompare(String(b)))
      
  return subset
}

console.log(getUniqueSortedCombinations([0,1,2,3]))
Emptybox
  • 121
  • 1
  • 10