Javascript Algorithm String permute

Description

Javascript Algorithm String permute

function permutations(str){
    // util function swap
    function swap(ar,a,b){
        var tmp = ar[a];
        ar[a] = ar[b];//www  .  j  a v  a2  s.c  om
        ar[b] = tmp;
    } 
    /**
     * recursive function
     * @param {Array} buff output buffer
     * @param {Array} arr representing elements of input string
     * @param {number} start
     * @param {number} end
     */ 
    function permute(buff,arr,start,end){
        var i,range = end-start;
        if(end-start==1){
            buff.push(arr.join("")); // output
        } else {
            for(i=0;i<range;i++){
                swap(arr,start,start+i);
                permute(buff,arr,start+1,end);
                swap(arr,start,start+i);
            }
        }
    }
    
    
    var buff = [];
    permute(buff,str.split(""),0,str.length);
    return buff;
}

console.log(permutations("abc"));

Another implementation

function permutations(str){
    function rotate(ar,a,b){
      var i,save = ar[b-1];
      for(i=b-1;i>a;i--){
          ar[i]=ar[i-1];/* w ww .j a  v a  2 s . c  o m*/
      }
      ar[a]=save;
    }
    function permute(buff,arr,start,end){
        var i,range = end-start;
        if(end-start==1){
            buff.push(arr.join(""));
        } else {
            for(i=0;i<range;i++){
                rotate(arr,start,end);
                permute(buff,arr,start+1,end);
            }
        }
    }
    var buff = [];
    permute(buff,str.split(""),0,str.length);
    return buff;
}

console.log(permutations("1234"));



PreviousNext

Related