Permutations in JavaScript?

前端 未结 30 2662
不思量自难忘°
不思量自难忘° 2020-11-21 06:52

I\'m trying to write a function that does the following:

  • takes an array of integers as an argument (e.g. [1,2,3,4])
  • creates an array of all the possib
30条回答
  •  广开言路
    2020-11-21 07:17

    Fastest, most (resorces) effective and most elegant version nowadays (2020)

    function getArrayMutations (arr, perms = [], len = arr.length) {
      if (len === 1) perms.push(arr.slice(0))
    
      for (let i = 0; i < len; i++) {
        getArrayMutations(arr, perms, len - 1)
    
        len % 2 // parity dependent adjacent elements swap
          ? [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]]
          : [arr[i], arr[len - 1]] = [arr[len - 1], arr[i]]
      }
    
      return perms
    }
    
    const arrayToMutate = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    const startTime = performance.now()
    const arrayOfMutations = getArrayMutations(arrayToMutate)
    const stopTime = performance.now()
    const duration = (stopTime - startTime) / 1000
    
    console.log(`${arrayOfMutations.length.toLocaleString('en-US')} permutations found in ${duration.toLocaleString('en-US')}s`)

提交回复
热议问题