Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate all possible combinations of the values in an array JS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["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))

>Solution :

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))
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading