Nodejs Array Permutation permutations(n)

Here you can find the source of permutations(n)

Method Source Code

/* Generate all permutations.
 * Use it with n = Array.length */

Array.prototype.permutations = function(n){
  var perms = [],
      array = this;//  w  w w.j  a  v  a  2s.  com
  var compute_perms = function(n){
    if(n==1)
      perms.push(array.join(''));
    else{
      for(var i=0; i!=n; i++){
        compute_perms(n-1);
        array.swap(n%2?0:i, n-1);
      }
    }
  }
  compute_perms(n);
  return perms;
}

Related

  1. permutationsArray_permutations()
    "use strict";
    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();
    ...
    
  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;
    };