Need all possible combinations of an array including the reverse of a combination too.
Eg:
var b = ['a1','b1','a','b'];
Need combinations as:
a1,b1,a,b
a1b1,a1a,a1b, b1a1,b1a,b1b, ......,
a1b1a,a1b1b,a1ab1,a1bb1,........,
a1b1ab,a1b1ba.....bab1a1
All 64 combinations (if array has 4 elements).
I found solution in java using ArrayList and Collection API, but right now I need a pure JavaScript ES5 solution.
I tried the following, but it only provides lesser combinations.
function getCombinations(chars) {
var result = [];
var f = function (prefix, chars) {
for (var i = 0; i < chars.length; i++) {
result.push(prefix + chars[i]);
f(prefix + chars[i], chars.slice(i + 1));
}
}
f('', chars);
return result;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…