Home > Software design >  Generate all possible combinations of the values in an array JS
Generate all possible combinations of the values in an array JS

Time:08-27

I've been struggling to get my code to work, but I'm new to recursion and permutation, so couldn't make it work, but what I would like to do is something to get all possible combinations of the values in an array, also including repeated values like "11".

For instance, let's say I have this array:

const array = ["1","2","3"]

What I would like to get from this array is something like this:

["11","12","13","21","22","23","31","32","33"]

I have seen lots of questions related to what I wanna do, but I haven't seen anything that shows repeated values as well and I'm kind of confused. Additionally, the example above is only showing repeated values like 11 and not 11111111 just as an example of a limit that I would like to have. Let's say that I want every possibility to be maximum 2 characters long. Like the code that I have below.

I got to find this, which is similar to what I want, but it just doesn't include repeated values

function generate(list, size=list.length) {
    if (size > list.length) return [];
    else if (size == 1) return list.map(d=>[d]); 
    return list.flatMap(d => generate(list.filter(a => a !== d), size - 1).map(item => [d, ...item]));
}
const list = ["1","2","3"]
console.log(generate(list,2))

CodePudding user response:

You can do this very simply with two nested for loops.

const array = ["1","2","3"]
let out = []

for (let i = 0; i < array.length; i  ) {
  for (let j = 0; j < array.length; j  ) {
    out.push(array[i]   array[j]);
  }
}

console.log(out);

CodePudding user response:

Example for you using generators

console.log([...permutate(['1', '2', '3'], 2)])
console.log([...permutate(['1', '2', '3'], 3)])

function* permutate(items, count) {
  yield* req([])

  function* req(array) {
    if (array.length == count) {
      yield array.join('')
      return
    }
    for (const item of items) {
      yield* req(array.concat(item))
    }
  }
}

The same using recursion with array

console.log(permutate(['1', '2', '3'], 2))
console.log(permutate(['1', '2', '3'], 3))

function permutate(items, count) {
  const results = []

  req([])

  return results

  function req(array) {
    if (array.length == count) {
      results.push(array.join(''))
      return
    }
    for (const item of items) {
      req(array.concat(item))
    }
  }
}

  • Related