Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

多维数组全排列 #81

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

多维数组全排列 #81

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@kangkang123269
Copy link

  1. 循环递归
function permute(arr) {
  if (arr.length === 1) return arr[0];
  
  let result = [];
  
  for (let i = 0; i < arr.length; i++) {
    let restArr = [...arr.slice(0, i), ...arr.slice(i + 1)];
    for(let sub of permute(restArr)) {
      result.push([arr[i], ...sub]);
    }
  }
  
  return result;
}

let testArr = [[1,2],[3,4],[5,6]];
console.log(permute(testArr)); 
// 输出:[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2 ,3 ,5] ,[2 ,3 ,6] ,[2 ,4 ,5] ,[2 ,4 ,6]]
  1. reduce
function generateCombinations(arr) {
    return arr.reduce((acc, val) => {
        return acc.map(v => val.map(item => [...v, item])).flat();
    }, [[]]);
}

let testArr = [[1, 2], [3, 4], [5, 6]];
console.log(generateCombinations(testArr)); 
// 输出:[[1 ,3 ,5] ,[1 ,3 ,6] ,[1 ,4 ,5] ,[1 ,4 ,6] ,[2 ,3 ,5] ,[2 ,3 ,6] ,[2 ,4 ,5],[2,4,6]]

@gswysy
Copy link

gswysy commented Mar 3, 2024

思路:先两两结合,得到结果再跟后面的结合。
例如先 ['A','B'] 跟 ['a','b'] 结合得到结果 [['A','a'],['A','b'],['B','a'],['B','b']] ,然后再跟 [1,2] 结合得到最终结果

let arr = [['A', 'B'],['a', 'b'],[1, 2]];

function permute(arr) {
    let res = arr[0].map(item => [item])
    for (let i = 1; i < arr.length; i++) {
        let list = arr[i]
        let temp = []
        for (const item of res) {
            temp = [...temp, ...list.map(i => [...item, i])]
        }
        res = temp
    }
    return res
}
console.log(permute(arr))
//输出
// [
//     [ 'A', 'a', 1 ],
//     [ 'A', 'a', 2 ],
//     [ 'A', 'b', 1 ],
//     [ 'A', 'b', 2 ],
//     [ 'B', 'a', 1 ],
//     [ 'B', 'a', 2 ],
//     [ 'B', 'b', 1 ],
//     [ 'B', 'b', 2 ]
// ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants