Created
December 11, 2017 22:07
-
-
Save RickGriff/020afe293c2d656bd68e43bbdfc74e88 to your computer and use it in GitHub Desktop.
Codewars Bonus Challenge 4 - Find The Sum of Diagonal 1's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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