Skip to content

Instantly share code, notes, and snippets.

@RickGriff
Created December 11, 2017 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickGriff/020afe293c2d656bd68e43bbdfc74e88 to your computer and use it in GitHub Desktop.
Save RickGriff/020afe293c2d656bd68e43bbdfc74e88 to your computer and use it in GitHub Desktop.
Codewars Bonus Challenge 4 - Find The Sum of Diagonal 1's
#Given a "square" array of subarrays, find the sum of values from the first value of the first array,
#the second value of the second array, the third value of the third array, and so on...
#Example 1:
#exampleArray = [[1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1]]
#diagonalSum(exampleArray) # => 4
#Extra Credit: Try to complete this exercise in three lines or less!
My Solution:
def diagonalSum(matrix)
sum = 0
matrix.each{ |arr| sum += arr[matrix.index(arr)] } #As the matrix is symmetric, the index of the diagonal element in the inner array matches that array's index in the outer array.
sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment