Aks*_*vas 5 javascript algorithm combinatorics
需要数组的所有可能组合,包括组合的逆向。
例如:
var b = ['a1','b1','a','b'];
Run Code Online (Sandbox Code Playgroud)
需要组合为:
a1,b1,a,b
a1b1,a1a,a1b, b1a1,b1a,b1b, ......,
a1b1a,a1b1b,a1ab1,a1bb1,........,
a1b1ab,a1b1ba.....bab1a1
Run Code Online (Sandbox Code Playgroud)
所有 64 种组合(如果数组有 4 个元素)。我使用 ArrayList 和 Collection API 在 java 中找到了解决方案,但现在我需要一个纯 JavaScript ES5 解决方案。
我尝试了以下方法,但它只提供了较少的组合。
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;
}
Run Code Online (Sandbox Code Playgroud)
让我们用文字表达您的请求:对于每个起始元素,附加其余元素的所有组合的所有排列。
function f(A, comb=[], result=[comb]){
return A.reduce((acc, a, i) => acc.concat(f(A.slice(0,i).concat(A.slice(i+1)), comb.concat(a))), result);
}
console.log(JSON.stringify(f(['a', 'b', 'c', 'd'])));Run Code Online (Sandbox Code Playgroud)
一个简单的递归可以解决这个问题。一探究竟:
function getCombinations(chars) {
let combinations = [];
chars.forEach((char, i) => {
let word = '';
buildWord(word + char, [i], chars, combinations)
});
return combinations;
}
function buildWord(word, usedIndexes, chars, combinations) {
combinations.push(word);
chars.forEach((char, i) => {
if (usedIndexes.indexOf(i) === -1) {
let newUsedIndexesArray = Array.from(usedIndexes);
newUsedIndexesArray.push(i);
buildWord(word + char, newUsedIndexesArray, chars, combinations)
}
});
}
console.log('Total: ' + getCombinations(['a1', 'b1', 'a', 'b']).length)
console.log(getCombinations(['a1', 'b1', 'a', 'b']))Run Code Online (Sandbox Code Playgroud)