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
4.3k views
in Technique[技术] by (71.8m points)

将数组转换成带排序的二维数组?

比如一个普通数组:

[1,3,5,2,7,8,9,0]

我想转换成

[
 [0,0,1],[0,1,3],[0,2,5],
 [1,0,2],[1,1,7],[1,2,8],
 [2,0,9],[2,1,0]
]

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

1 Answer

0 votes
by (71.8m points)

就是创建一个矩阵,那么方法很多,具体要看你的需求,比如数组长度不够和超出矩阵怎么办,下面是封装的一个函数

function creatMatrix(arr, list) {
  let result = []
  arr.forEach((item, index) => {
    let res = [item]
    list.reduce((num, column) => {
      res.unshift(num % column)
      return num / column | 0
    }, index)
    result.push(res)
  })
  return result
}

let arr = [1,3,5,2,7,8,9,0]
//生成一个 2 * 2 * 2 的矩阵
creatMatrix(arr, [2, 2, 2])
//[[0,0,0,1],[0,0,1,3],[0,1,0,5],[0,1,1,2],[1,0,0,7],[1,0,1,8],[1,1,0,9],[1,1,1,0]]

//生成一个 3 * 3 的矩阵
creatMatrix(arr, [3, 3])
//[[0,0,1],[0,1,3],[0,2,5],[1,0,2],[1,1,7],[1,2,8],[2,0,9],[2,1,0]]

//生成一个 3 * 4 * 5 的矩阵
creatMatrix(arr, [3, 4, 5])
//[[0,0,0,1],[0,0,1,3],[0,0,2,5],[0,1,0,2],[0,1,1,7],[0,1,2,8],[0,2,0,9],[0,2,1,0]]

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

...