如何在javascript中对矩阵的所有列进行排序?

时间:2018-03-11 12:56:13

标签: javascript

我正在尝试解决这个问题,但我可以使用一些帮助。我想按升序对此矩阵的所有列进行排序,但此代码仅对第一个列进行排序。知道我该怎么办?

 <script>
 var matrix = [
  [ 0, 8, 1, 1, 10, 6 ],
  [ 6, 8, 7, 0, 3, 9],
  [ 0, 7, 6, 8, 6, 5],
  [ 4, 0, 2, 7, 2, 0],
  [ 4, 4, 5, 7, 5, 1]
];

var colSort = matrix.sort(function(a,b) {
       return  a[0]-b[0]
           });
console.log(colSort);

// sums of one specific row
var rowSum = matrix[3].reduce((a, b) => a + b);

// sums of columns
var colSum = matrix.reduce((a, b) => a.map((x, i) => x + b[i]));

console.log(rowSum);
console.log(colSum);
</script>

这应该在排序后输出:

[[0, 0, 1, 0, 2, 0], 
[0, 4, 2, 1, 3, 1], 
[4, 7, 5, 7, 5, 5],
[4, 8, 6, 7, 6, 6], 
[6, 8, 7, 8, 10, 9]] 

3 个答案:

答案 0 :(得分:1)

你应该做的是翻转矩阵,使所有行都是列,所有列都是行,使用这个zip函数:

var zip = rows => rows[0].map((_,c) => rows.map(row=>row[c]));
var flipped = zip(matrix);

然后你可以对每一行进行排序:

for (var i = 0; i < flipped.length; i++) {
    flipped[i] = flipped[i].sort((a, b) => a - b);
}

然后将其翻转:

var finalUnflippedResult = zip(flipped);

总结你得到:

var zip = rows => rows[0].map((_,c) => rows.map(row=>row[c]));
var flipped = zip(matrix);
for (var i = 0; i < flipped.length; i++) {
    flipped[i] = flipped[i].sort((a, b) => a - b);
}
var result = zip(flipped);

答案 1 :(得分:0)

或者你可以在评论中提到这一点。

var matrix = [
  [ 0, 8, 1, 1, 10, 6 ],
  [ 6, 8, 7, 0, 3, 9],
  [ 0, 7, 6, 8, 6, 5],
  [ 4, 0, 2, 7, 2, 0],
  [ 4, 4, 5, 7, 5, 1]
];

matrix=matrix.map((col, i) => matrix.map(row => row[i]));//take transpose of matrix
matrix.forEach(function(e){  //sort the rows of martix
  e.sort()
});
console.log(matrix.map((col, i) => matrix.map(row => row[i]))); //transpose it again

答案 2 :(得分:0)

&#13;
&#13;
        var matrix = [
            [0, 8, 1, 1, 10, 6],
            [6, 8, 7, 0, 3, 9],
            [0, 7, 6, 8, 6, 5],
            [4, 0, 2, 7, 2, 0],
            [4, 4, 5, 7, 5, 1]
        ];

        console.log(matrix);

        var colsArr = [];

        function takeColumn(arr, colNum) {
            var resultColumn = [];

            for (let i = 0; i < arr.length; i++) {
                resultColumn.push(matrix[i][colNum]);
            }

            return resultColumn.sort(function (a, b) {
                return a - b;
            });
        };

        for (let r = 0; r < 6; r++) {
            colsArr.push(takeColumn(matrix, r));
        }
        console.log(colsArr);

        transpose = arr => arr[0].map((x, i) =>arr.map(x => x[i]));

        console.log(transpose(colsArr));
&#13;
&#13;
&#13;