Created
January 29, 2009 12:58
-
-
Save snj14/54528 to your computer and use it in GitHub Desktop.
permutation & combination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment