全排列
普通对象全排列
function permute(arr) {
function generatePermutations(currentArr, remainingArr) {
if (remainingArr.length === 0) {
permutations.push(currentArr);
} else {
for (let i = 0; i < remainingArr.length; i++) {
const newArr = currentArr.slice();
newArr.push(remainingArr[i]);
const restArr = remainingArr.slice(0, i).concat(remainingArr.slice(i + 1));
generatePermutations(newArr, restArr);
}
}
}
const permutations = [];
generatePermutations([], arr);
return permutations;
}
// 示例用法
const inputArray = ['A', 'B', 1, 2];
const result = permute(inputArray);
console.log(result);
不定长二维数组的全排列
// 输入 [['A', 'B', ...], [1, 2], ['a', 'b'], ...]
// 输出 ['A1a', 'A1b', ....]
let arrays = [
['A', 'B', 'C'],
[1, 2],
['a', 'b']
];
function getArrayByArrays(inputArray) {
let result = [''];
for (let i = 0; i < inputArray.length; i++) {
result = getValuesByArray(result, inputArray[i]);
}
return result;
}
function getValuesByArray(res, remainingArray) {
let midArray = [];
for (let i = 0; i < res.length; i++) {
for (let j = 0; j < remainingArray.length; j++) {
midArray.push(res[i] + remainingArray[j]);
}
}
return midArray;
}
let result = getArrayByArrays(arrays);
console.log('result', result);