Matrix Trace
Description:
Calculate the trace of a square matrix. A square matrix has n
rows and n
columns, where n
is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or nil/None
if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).
The trace of an n-by-n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A.
A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.
For example, the following code...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
represents the matrix
|1 2 3|
|4 5 6|
|7 8 9|
which has a trace of 1 + 5 + 9 = 15
.
You can read more about the trace of a matrix at these sources:
Note: The Matrix
class is disabled.
Similar Kata:
Stats:
Created | Apr 5, 2015 |
Published | Apr 5, 2015 |
Warriors Trained | 1238 |
Total Skips | 20 |
Total Code Submissions | 3053 |
Total Times Completed | 898 |
Ruby Completions | 74 |
Python Completions | 811 |
Haskell Completions | 35 |
Total Stars | 20 |
% of votes with a positive feedback rating | 93% of 168 |
Total "Very Satisfied" Votes | 146 |
Total "Somewhat Satisfied" Votes | 21 |
Total "Not Satisfied" Votes | 1 |
Total Rank Assessments | 7 |
Average Assessed Rank | 6 kyu |
Highest Assessed Rank | 6 kyu |
Lowest Assessed Rank | 7 kyu |