Last active
May 2, 2019 12:02
-
-
Save avosalmon/6ffe9b43c735aafe76c803966b4d0fd6 to your computer and use it in GitHub Desktop.
This file contains 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
require 'minitest/autorun' | |
class Matrix | |
# @param {Integer[][]} matrix | |
# @return {Boolean} | |
def toeplitz?(matrix) | |
return false if square?(matrix) | |
matrix.each_with_index do |row, row_index| | |
row.each_with_index do |value, column_index| | |
return false unless value.is_a? Integer | |
diagonal_value = matrix[row_index-1][column_index-1] | |
if row_index > 0 && column_index > 0 && value != diagonal_value | |
return false | |
end | |
end | |
end | |
true | |
end | |
private | |
# @param {Integer[][]} matrix | |
# @return {Boolean} | |
def square?(matrix) | |
matrix.size > 0 && matrix.size == matrix.first.size | |
end | |
end | |
class MatrixTest < MiniTest::Unit::TestCase | |
def setup | |
@matrix = Matrix.new | |
end | |
def test_valid_toeplitz_matrix | |
input = [ | |
[1, 2, 3, 4], | |
[5, 1, 2, 3], | |
[4, 5, 1, 2], | |
[7, 4, 5, 1] | |
] | |
assert_equal @matrix.toeplitz?(input), true | |
end | |
def test_invalid_toeplitz_matrix | |
input = [ | |
[1, 2, 3, 4], | |
[5, 1, 6, 3], | |
[4, 5, 1, 2], | |
[7, 4, 5, 1] | |
] | |
assert_equal @matrix.toeplitz?(input), false | |
end | |
def test_non_square_matrix | |
input = [ | |
[1, 2, 3, 4], | |
[5, 1, 2, 3], | |
[4, 5, 1, 2] | |
] | |
assert_equal @matrix.toeplitz?(input), false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment