snj14 (owner)

Revisions

gist: 54528 Download_button fork
public
Description:
permutation & combination
Public Clone URL: git://gist.github.com/54528.git
Embed All Files: show embed
permutation & combination #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
function permutation(array){
    return array.reduce(function(prev,current){
        var res = [];
        prev.forEach(function(pe){
            if(!pe['length']) pe = [pe];
            return current.forEach(function(ce){
                res.push(pe.concat([ce]))
            })
        })
        return res
    })
}
 
function combination(array){
    return array.reduce(function(prev,current){
        var res = [];
        prev.forEach(function(pe){
            if(!pe['length']) pe = [pe];
            return current.forEach(function(ce){
                var r = pe.concat([ce])
                r.sort()
                if(!res.some(function(f){
                    return f.every(function(ff, i){
                        return ff == r[i]
                    })
                })){
                    res.push(r)
                }
            })
        })
        return res
    })
}
var a = [1,2]
var b = [2,1]
var c = [2,1]
var d = [a,b,c]
console.log('----- all combinations')
combination(d).forEach(function(e){
  console.log(e)
})
console.log('----- all permutations')
permutation(d).forEach(function(e){
  console.log(e)
})
 
// ----- all combinations
// [1, 2, 2]
// [1, 1, 2]
// [1, 1, 1]
// [2, 2, 2]
// ----- all permutations
// [1, 2, 2]
// [1, 2, 1]
// [1, 1, 2]
// [1, 1, 1]
// [2, 2, 2]
// [2, 2, 1]
// [2, 1, 2]
// [2, 1, 1]