1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-211/#TASK1 3 # 4 # Task 1: Toeplitz Matrix 5 # ======================= 6 # 7 # You are given a matrix m x n. 8 # 9 # Write a script to find out if the given matrix is Toeplitz Matrix. 10 # 11 ## A matrix is Toeplitz if every diagonal from top-left to bottom-right has the 12 ## same elements. 13 # 14 ## Example 1 15 ## 16 ## Input: @matrix = [ [4, 3, 2, 1], 17 ## [5, 4, 3, 2], 18 ## [6, 5, 4, 3], 19 ## ] 20 ## Output: true 21 # 22 ## Example 2 23 ## 24 ## Input: @matrix = [ [1, 2, 3], 25 ## [3, 2, 1], 26 ## ] 27 ## Output: false 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # We just need to walk all diagonals and check if all numbers are 36 # the same. But actually it's easier to walk the matrix and check 37 # whether the element to the right bottom of the current one differs 38 # from the current one. When we do that everywhere we can know 39 # whether all diagonals have the same number everywhere as well, 40 # so let's do that. 41 42 toeplitz([ [4, 3, 2, 1], 43 [5, 4, 3, 2], 44 [6, 5, 4, 3] ]); 45 toeplitz([ [1, 2, 3], 46 [3, 2, 1] ]); 47 48 sub toeplitz { 49 my $matrix = shift; 50 die "Not a matrix" unless is_matrix($matrix); 51 # get the dimensions of the matrix 52 my $lines = scalar(@$matrix); 53 my $columns = scalar(@{$matrix->[0]}); 54 # for each line and column except the last one, compare the element 55 # at that position and the one on the right bottom of it 56 foreach my $i (0..$lines-2) { 57 foreach my $j (0..$columns-2) { 58 my $this_element = $matrix->[$i]->[$j]; 59 my $next_diagonal_element = $matrix->[$i+1]->[$j+1]; 60 if ($this_element != $next_diagonal_element) { 61 print "Output: false\n"; 62 return; 63 } 64 } 65 } 66 print "Output: true\n"; 67 } 68 69 # helper function to check if we actually have a matrix 70 sub is_matrix { 71 my $matrix = shift; 72 return 0 unless ref($matrix) eq "ARRAY"; 73 my $columns = scalar(@{$matrix->[0]}); 74 foreach my $line (@$matrix) { 75 return 0 unless scalar(@$line) == $columns; 76 } 77 return 1; 78 } 79