0

How can I get a list of all the possible permutations of an array of length L using iteration?

The output elements should contain only permutations of the same length as that of the original array.

EG: {1,2,3}

OUTPUT: {1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}

Sample Code (Not Working)

var swap = function(z, l, j) {
    var e = z.slice(0);
    var k = e[l];
    e[l] = e[j];
    e[j] = k;
    return e;
};
var _permu = function(p, i) {

if(i == p.length)
    console.log("com", p.join(""));
    for (var j = 0; j < i; j++) {
        var t = swap(p, j, i);
        _permu(t, i - 1);
    }
};
DasKrümelmonster
  • 5,816
  • 1
  • 24
  • 45
tusharmath
  • 10,622
  • 12
  • 56
  • 83
  • Can't think of anything. – tusharmath Mar 29 '13 at 16:50
  • 7
    -1 You should read [What have you tried](http://whathaveyoutried.com). Even bad code is better than no code when posting this kind of question. – Dan Pichelman Mar 29 '13 at 16:59
  • In ruby (not that I encourage it) `[1, 2, 3].permutation(3).to_a => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]` -- the docs for this can be seen at [Array](http://www.ruby-doc.org/core-2.0/Array.html#method-i-permutation) or [clojure](http://clojure.github.com/math.combinatorics/) or use [guava collections2](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Collections2.html#permutations(java.util.Collection)) -- otherwise you are looking for the algorithms specified in http://en.wikipedia.org/wiki/Permutation –  Mar 29 '13 at 18:36
  • As I was trying to point out in my previous comment and missed - nearly every language has a library (either core to the language or added on) that provides this functionality. This is the suggested way of getting the permutations. If that is the answer, you need to specify the language and search google. If you are after writing it yourself from scratch, please explain the full problem that you are having and what you have tried so that we one can identify the proper solution to the problem. –  Mar 29 '13 at 18:47
  • I am looking for this solution in Javascript. – tusharmath Mar 29 '13 at 19:17
  • Is iteration a strict requirement? Would a recursive solution work? – templatetypedef Mar 31 '13 at 00:27

0 Answers0