Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k 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 Reply

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' ]
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...