Toeplitz Matrix in java
Toeplitz matrix where all the diagonals are equal.
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
import java.util.*; | |
public class ToeplizMatrix { | |
public static int toeplizMatrix(int[][] input1) | |
{ | |
int output=0,output1=0,output2=0,tally=0; | |
int rows=input1.length;int columns=input1[0].length; | |
//The below method checks the center diagonal to all diagonals at the right side of matrix. | |
for(int a=0;a<columns;a++){ | |
tally=input1[0][a]; | |
for(int b=0,c=a;b<rows && c<columns;b++,c++){ | |
if(tally==input1[b][c]){ | |
output1=1; | |
} | |
else{ | |
output1=-1; | |
break; | |
} | |
} | |
if(output1==-1){ //This breaks the loop if diagonals are not matching | |
break; | |
} | |
} | |
//The below method checks the after the center diagonal to all diagonals at the left side of matrix. | |
for(int i=1;i<rows;i++){ | |
tally=input1[i][0]; | |
for(int j=i,k=0;j<rows && k<columns;j++,k++){ | |
if(tally==input1[j][k]){ | |
output2=1; | |
} | |
else{ | |
output2=-1; | |
break; | |
} | |
} | |
if(output2==-1){ //This breaks the loop if diagonals are not matching | |
break; | |
} | |
} | |
if(output1+output2>0) | |
output=1; | |
else | |
output=-1; | |
return output; | |
} | |
public static void main(String [] args){ | |
Scanner in = new Scanner(System.in); | |
int output = 0; | |
int ip1_rows = 0; | |
int ip1_cols = 0; | |
ip1_rows = Integer.parseInt(in.nextLine().trim()); | |
ip1_cols = Integer.parseInt(in.nextLine().trim()); | |
int[][] ip1 = new int[ip1_rows][ip1_cols]; | |
for(int ip1_i=0; ip1_i<ip1_rows; ip1_i++) { | |
for(int ip1_j=0; ip1_j<ip1_cols; ip1_j++) { | |
ip1[ip1_i][ip1_j] = in.nextInt(); | |
} | |
} | |
output = toeplizMatrix(ip1); | |
System.out.println(String.valueOf(output)); | |
in.close(); | |
} | |
} |
Input:
4
5
6 7 8 9 2
4 6 7 8 9
1 4 6 7 8
0 1 4 6 7
Output: 1
Input:
3
3
1 2 3
4 5 6
7 8 9
Output: -1
4
5
6 7 8 9 2
4 6 7 8 9
1 4 6 7 8
0 1 4 6 7
Output: 1
Input:
3
3
1 2 3
4 5 6
7 8 9
Output: -1
Comments
Post a Comment