Find next unique array combination

Lets say I have an array

let arr = [a, b, c];

The unique combinations for the array would be [a], [b], [c], [a, b], [a, c], [b, c] and [a, b, c].

Using indexes it would be [0], [1], [2], [0, 1], [0, 2], [1, 2] and [0, 1, 2].

Does anyone know a good way of dynamicly getting the next unique array combination given the indexes of the current combination as input.

For example

let a = foo(arr, [1]);
// a = [c] or [2]

let b = foo(arr, [2]);
// b = [a, b] or [0, 1]

And by dynamicly I mean that I dont want to generate all possible unique combinations and then iterate that array.

Thanks!

EDIT

I made another try solving this and ended up with this. Maybe I should rephrase the question and ask for possible improvements for the solution.

let arr = ['a', 'b', 'c', 'd', 'e'];

let input = [0];

for (let i = 0; i < 31; i++) {
  input = foo(arr, input);
  console.log(input.map(index => arr[index]));
}

function foo(a, b) {
  let i = b.length - 1;
  while (i >= 0) {
    if (b[i] < a.length - (b.length - i)) {
      b[i]++;
      break;
    }
    i--;
  }
  if (i === -1) {
    b.unshift(0);
    i++
  }
  if (b.length > a.length) {
    return [0];
  }
  for (let j = i + 1; j < b.length; j++) {
    b[j] = b[j - 1] + 1;
  }
  return b;
}


Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)