js二维数组如何横向穷举?
假设有一个二维数组:
let arr = [
['1','2','3'],
['a','b','c'],
]
怎么样才可以实现"横向的穷举",不知道我的描述是否准确,结果如下:
['1','2','3'],
['1','b','3'],
['1','2','c'],
['a','2','3'],
['a','b','3'],
['a','b','c'],
想要的效果是:结果中的数组,是不会出现原数组的同一个下标的数据,比如:1 和 a 不会在同一个结果数组中出现,同理,2&b,3&c也是如此
回答
我理解一下题目:
二维数组 arr 每一行长度相等,求每一列对应字符的全排列
全排列用递归:
const matrix = [ ['a', 'b', 'c'],
['1', '2', '3']
]
// 输入新字符和已有排列, 返回新排列
const fn = (resultArr, matrix, index = 0) => {
if (index >= matrix[0].length) return resultArr
const newResult = []
resultArr.forEach(arr => {
matrix.forEach(row => {
newResult.push([...arr, row[index]])
})
})
return fn(newResult, matrix, index + 1)
}
console.log(fn([''], matrix))
输出:
[ [ 'a', 'b', 'c' ],
[ 'a', 'b', '3' ],
[ 'a', '2', 'c' ],
[ 'a', '2', '3' ],
[ '1', 'b', 'c' ],
[ '1', 'b', '3' ],
[ '1', '2', 'c' ],
[ '1', '2', '3' ]
]
就是组合吧。['1', 'a'],['2', 'b'], ['3', 'c']
每组各抽取一个出来得到结果。
结果:
[ ["1","2","3"],
["a","2","3"],
["1","b","3"],
["a","b","3"],
["1","2","c"],
["a","2","c"],
["1","b","c"],
["a","b","c"]
]
具体可看https://wintc.top/article/17
以上是 js二维数组如何横向穷举? 的全部内容, 来源链接: utcz.com/a/65449.html