0

I wrote a permutation function. when the function takes a string, it works well. but when i tried to use the same method to permutation array, that does not work anymore. Where comes from the problem?

so the working code with string is like below, this one works well:

const swap = function (str, l, r){
    //! mistake
    let arr = str.split('')
    let tmp = arr[l]
    arr[l] = arr[r]
    arr[r] = tmp
    return str = arr.join('')
}
const permutation =  function(str, l, r, result){
    if(l == r)
        result.add(str)
    else{
        for(let i=l; i<=r; i++){
            str = swap(str, l, i)
            permutation(str, l+1, r, result)
            str = swap(str, l, i)
        }
    }
}
const permut = function(str){
    let r = str.length - 1
    if(r===0)
        return []
    result = new Set()
    permutation(str, 0, r, result)
    return Array.from(result)
}

console.log(permut('abc'))

the function below takes an array as parameter. it is quite the same as the function above, but it does not work:

const swapA = function(array, index1, index2){
    let temp = array[index1]
    array[index1] = array[index2]
    array[index2] = temp
    return array
}

const permutationRecursive = function(array, l, r, f){
  console.log(array, 'l')
    if(l==r){
       //???? why not work, console.log(array)->show all correct array,                       
       //but the result of f is not correct
       f.add(array)
    }
    else{
        for(let i=l; i<=r; i++){
            array = swapA(array, l, i)
            permutationRecursive(array, l+1, r,f)
            array = swapA(array, l, i)
        }
    }
}

function permutateOuter(array){
    let len = array.length - 1
    let f = new Set()
    permutationRecursive(array, 0,len,f)
    return f
}
console.log(permutateOuter([1,2,3]))


lfan3
  • 11
  • 1
  • `swapA` does not create a new array, it just swaps two elements and returns the identical object that you passed in. You're always adding the same array instance to the set. – Bergi May 30 '20 at 14:44
  • @Bergi ah!! Thanks alot! That is very helpful! – lfan3 Jun 01 '20 at 21:18

0 Answers0