Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function ascendingSort(array) {
  3.     return array.sort(function (a, b) {
  4.         return b - a;
  5.     }).reverse();
  6. }
  7.  
  8. function descendingSort(array) {
  9.     return array.sort(function (a, b) {
  10.         return b - a;
  11.     });
  12. }
  13. // ascending sort for even rows
  14. // descending sort for odd rows
  15.  
  16. function sortRowsInMatrix(matrix) {
  17.     var currentRow = [];
  18.  
  19.     for (var i = 0; i < matrix.length; i++) {
  20.         for (var j = 0; j < matrix.length; j++) {
  21.             currentRow.push(matrix[i][j]);
  22.         }
  23.         if (i % 2 === 0) {
  24.             currentRow = ascendingSort(currentRow);
  25.         }
  26.         else {
  27.             currentRow = descendingSort(currentRow);
  28.         }
  29.         for (var j = 0; j < matrix.length; j++) {
  30.             matrix[i][j] = currentRow[j];
  31.         }
  32.         currentRow = [];
  33.     }
  34.  
  35.     return matrix;
  36. }
  37.  
  38. var matrix = [[3, 2, 1], [4, 5, 6], [9, 8, 7]];
  39. console.log(sortRowsInMatrix(matrix));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement