javascript permutation generator with permutation length parameter

后端 未结 4 1059
鱼传尺愫
鱼传尺愫 2020-12-05 22:45

I\'ve seen a few generators out there but they all make a squared matrix. For example, you give it a list of three items and it\'ll assume the output of the length is also t

4条回答
  •  抹茶落季
    2020-12-05 23:04

    If you're looking for an answer based on performance, you can use the length of the array as a numerical base, and access the elements in the array based on this base, essentially replacing actual values from the base with the values in your array, and accessing each of the values in order, using a counter:

    const getCombos = (arr, len) => {
      const base = arr.length
      const counter = Array(len).fill(base === 1 ? arr[0] : 0)
      if (base === 1) return [counter]
      const combos = []
      const increment = i => {
        if (counter[i] === base - 1) {
          counter[i] = 0
          increment(i - 1)
        } else {
          counter[i]++
        }
      }
    
      for (let i = base ** len; i--;) {
        const combo = []
        for (let j = 0; j < counter.length; j++) {
          combo.push(arr[counter[j]])
        }
        combos.push(combo)
        increment(counter.length - 1)
      }
    
      return combos
    }
    
    const combos = getCombos([1, 2, 3], 3)
    console.log(combos)

    For smaller use cases, like the example above, performance shouldn't be an issue, but if you were to increase the size of the given array from 3 to 10, and the length from 3 to 5, you have already moved from 27 (33) combinations to 100,000 (105), you can see the performance difference here:

提交回复
热议问题