How to check if a matrix is Toeplitz or not in Go

1 Answer

0 votes
// A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements
 
package main

import (
	"fmt"
)

func isToeplitz(matrix [][]int) bool {
	rows := len(matrix)
	cols := len(matrix[0])

	for i := 1; i < rows; i++ {
		for j := 1; j < cols; j++ {
			fmt.Printf("%d %d - %d : %d\n", i, j, matrix[i][j], matrix[i-1][j-1])
			if matrix[i][j] != matrix[i-1][j-1] {
				return false
			}
		}
		fmt.Println("-----------")
	}

	return true
}

func main() {
	matrix := [][]int{
		{2, 7, 9, 8},
		{4, 2, 7, 9},
		{3, 4, 2, 7},
		{0, 3, 4, 2},
		{6, 0, 3, 4},
	}

	if isToeplitz(matrix) {
		fmt.Println("Matrix is a Toeplitz")
	} else {
		fmt.Println("Matrix is not a Toeplitz")
	}
}



/*
run:

1 1 - 2 : 2
1 2 - 7 : 7
1 3 - 9 : 9
-----------
2 1 - 4 : 4
2 2 - 2 : 2
2 3 - 7 : 7
-----------
3 1 - 3 : 3
3 2 - 4 : 4
3 3 - 2 : 2
-----------
4 1 - 0 : 0
4 2 - 3 : 3
4 3 - 4 : 4
-----------
Matrix is a Toeplitz

*/

 



answered Jan 31, 2025 by avibootz
edited Jan 31, 2025 by avibootz

Related questions

1 answer 98 views
1 answer 110 views
1 answer 123 views
1 answer 99 views
1 answer 124 views
1 answer 131 views
1 answer 116 views
...