Skip to content

Instantly share code, notes, and snippets.

@avosalmon
Last active May 2, 2019 12:02
Show Gist options
  • Save avosalmon/6ffe9b43c735aafe76c803966b4d0fd6 to your computer and use it in GitHub Desktop.
Save avosalmon/6ffe9b43c735aafe76c803966b4d0fd6 to your computer and use it in GitHub Desktop.
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