Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

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也是如此


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我理解一下题目:
二维数组 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' ]
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...