Nodejs Array Permutation permutationsArray_permutations()

Here you can find the source of permutationsArray_permutations()

Method Source Code

"use strict";// w w w  .  ja  va 2s . c o  m

Array.prototype.permutations = function Array_permutations() {
    if (this.length === 1) {
        return [this];
    }
    var permutations = [],
        tmp, fixed;
    for (var i=0; i<this.length; i++) {
        tmp = this.slice();
        fixed = tmp.splice(i, 1);
        tmp.permutations().forEach(function(partial){
            partial.unshift(fixed[0]);
            permutations.push(partial);
        });
    }
    return permutations;
};

String.prototype.permutations = function String_permutations() {
    return this.split('').permutations().map(function(item){
        return item.join('');
    });
};

Related

  1. permutations(n)
    Array.prototype.permutations = function(n){
      var perms = [],
          array = this;
      var compute_perms = function(n){
        if(n==1)
          perms.push(array.join(''));
        else{
          for(var i=0; i!=n; i++){
            compute_perms(n-1);
    ...
    
  2. permute(len)
    Array.prototype.permute = function(len) {
        var ret = [];
        for (var i = 0; i < this.length; i++) {
            var c = this[i];
            if (len > 1) {
                var sub = this.permute(len - 1);
                for (var j = 0; j < sub.length; j++) {
                    ret.push(c + sub[j]);
            } else return this;
        return ret;
    };