brewersfan1976

swap_diagonals.rb

Oct 16th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.30 KB | None | 0 0
  1. def swapDiagonals(matrix)
  2.     array = Array.new(matrix.length){Array.new matrix[0].length}
  3.     first_diagonal = Array.new
  4.     second_diagonal = Array.new
  5.     x = 0
  6.     y = 0
  7.    
  8.     # get first longest diagonal
  9.    
  10.     while (x < matrix.length)
  11.           first_diagonal[x] = matrix[x][y]
  12.           x = x + 1
  13.           y = y + 1
  14.     end
  15.    
  16.     # get second longest diagonal
  17.    
  18.     x = 0
  19.     y = matrix[0].length - 1
  20.    
  21.     while (x < matrix.length)
  22.           second_diagonal[x] = matrix[x][y]
  23.           x = x + 1
  24.           y = y - 1
  25.     end
  26.    
  27.     # swap the two diagonals
  28.    
  29.     x = 0
  30.     y = 0
  31.    
  32.     while (x < matrix.length)
  33.           array[x][y] = second_diagonal[x]
  34.           x = x + 1
  35.           y = y + 1
  36.     end
  37.    
  38.     x = 0
  39.     y = matrix[0].length - 1
  40.    
  41.     while (x < matrix.length)
  42.           array[x][y] = first_diagonal[x]
  43.           x = x + 1
  44.           y = y - 1
  45.     end
  46.    
  47.     x = 0
  48.     y = 0
  49.    
  50.     # fill in the rest
  51.    
  52.     while (x < matrix.length)
  53.         while (y < matrix[0].length)
  54.               if array[x][y] == nil then
  55.                  array[x][y] = matrix[x][y]
  56.               end
  57.                  
  58.               y = y + 1
  59.         end
  60.            
  61.         x = x + 1
  62.         y = 0
  63.     end
  64.        
  65.     return array
  66. end
Advertisement
Add Comment
Please, Sign In to add comment