Skip to content

Instantly share code, notes, and snippets.

@DavidGoussev
Created September 30, 2015 04:01
Show Gist options
  • Select an option

  • Save DavidGoussev/c2ab708ee440d2b23b88 to your computer and use it in GitHub Desktop.

Select an option

Save DavidGoussev/c2ab708ee440d2b23b88 to your computer and use it in GitHub Desktop.
matrices
(1)
def diagsum(matrix)
(0...matrix.length).map{ |i| matrix[i][i] }.reduce(:+)
end
# uses map enumerator for the array of matrix values - remember to use the three-dot notation as it omits the last value since array starts at 0
# matrix[i][i] indicates the array position of each diagonal value for each row (row, column will be the same value for a square matrix
# reduce(:+) is an enumerator method sums up the block values that were just mapped from the array
(2)
require 'matrix'
def diagsum(matrix)
Matrix[*matrix].trace
end
#uses matrix library's trace method, which sums up all diag values in a matrix. needs the splat operator to flatten the matrix array and return just values
(3)
def diagsum(matrix)
(0...matrix.size).inject(0) { |sum,i| sum + matrix[i][i] }
end
#uses an inject method on the matrix array - note .size works just as .length did in prev example - with a starting arg of (0)
#inject enumerates the sum and the individual values in the array (represented as i), adding each incremental value of matrix[i][i] against itself (the sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment