我需要增加字母,我需要将字母与组合匹配。
var allArrays = new Array(['a','c'],['b','e'],['r','s']);
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function (result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
console.log(getPermutation(allArrays));
其中['a','c']
a,b,r --->从位置
c,e,s --->到位置
对于剩余的数组也是如此。
我需要输出
"abr","abs","acr","acs","adr","ads","aer","aes","bbr","bbs","bcr","bcs","bdr","bds","ber","bes","cbr","cbs","ccr","ccs","cdr","cds","cer","ces"
但我得到的输出就像这样,
"abr","abs","aer","aes","cbr","cbs","cer","ces"
我只是在它们之间获得组合,但我正在努力增加所给出的字母,并且必须做组合。
答案 0 :(得分:2)
您可以先填补空白,然后应用getPermutation
。
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function (result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
var allArrays = new Array(['a', 'c'], ['b', 'e'], ['r', 's']);
allArrays.forEach(function (a) {
var value = parseInt(a[0], 36) + 1,
last = a.pop(),
lastValue = parseInt(last, 36);
while (value <= lastValue) {
a.push(value.toString(36));
value++;
}
});
console.log(allArrays);
console.log(getPermutation(allArrays));
.as-console-wrapper { max-height: 100% !important; top: 0; }
字母和任何数字的解决方案,无论顺序如何,都要检查类型并使用变量来递增/递减值。
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
return array[0].reduce(function (result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
}
var allArrays = new Array(['a', 'c'], ['e', 'b'], ['02', '04'], ['32', '29']);
allArrays.forEach(function (a) {
var length = a[1].length,
pad = isNaN(a[0]) ? ' ' : '0',
radix = isNaN(a[0]) ? 36 : 10,
value = parseInt(a[0], radix),
lastValue = parseInt(a.pop(), radix),
inc = +(lastValue >= value) || -1,
temp;
value += inc;
while (inc === 1 ? value <= lastValue : value >= lastValue) {
temp = value.toString(radix);
while (temp.length < length) {
temp = pad + temp;
}
a.push(temp);
value += inc;
}
});
console.log(allArrays);
console.log(getPermutation(allArrays));
.as-console-wrapper { max-height: 100% !important; top: 0; }