CC-13 : Find count of rows and columns that have same elements in the same order.
Description:
If a row and column of matrix are said to be same, if they contain same elements, in the same order. Given an integer 2d matrix arr, find and return the count of same row and column pairs.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| arr = { {2,4,5}, {2,2,3}, {3,7,9} }; |
Matrix has 1 equal pairs of rows and columns. |
| arr1 = { {2,4,2}, {2,3,3}, {2,3,3} } |
Matrix has 2 equal pairs of rows and columns. |
Pseudocode:
| The java method should accept following input parameters: arr(integer 2d array). |
| Initialize a variable named rows of type HashMap |
| Initialize a variable named sb of type StringBuilder. Initialize a variable named rowStr. |
| Iterate through arr using a for loop with cidx as a loop variable with initial value 0 and increment rIdx till it reaches arr[0].length-1:
Convert each integer at arr[rIdx][cIdx] to a String and append it to sb separated by a “*” symbol.
If rows does not contain key sb.toString(), then put key-value pair sb.toString() and 1 to rows.
If rows contains key sb.toString() with value freq, then put key-value pair sb.toString() and freq+1 to rows.
|
| Define int variable eqlRowColCnt=0. Declare variable colsStr of type String. |
| Iterate through arr using a for loop with cIdx as a loop variable with initial value 0 and increment cIdx till it reaches arr.length-1:
Iterate through arr using a for loop with rIdx as a loop variable with initial value 0 and increment rIdx till it reaches arr[0].length-1:
Convert each integer at arr[rIdx][cIdx] to a String and append it to sb separated by a “*” symbol.
If rows contains key sb.toString() then increment eqlRowColCnt by one.
|
| After above loop completes, eqlRowColCnt contains count of same rows and columns of arr. Return eqlRowColCnt. |
Code:
public int hashMapEqualRowsColumns(int[][] arr) throws Exception{
HashMap< String,Integer> rows=new HashMap< String,Integer>();
StringBuilder sb;
String rowStr;
for (int rIdx=0; rIdx < arr.length; rIdx++) {
sb=new StringBuilder();
for (int cIdx=0; cIdx < arr[0].length; cIdx++) {
sb.append((Integer.valueOf(arr[rIdx][cIdx]).toString()));
sb.append("*");
}
rowStr=sb.toString();
rows.put(rowStr, rows.getOrDefault(rowStr, 0)+1);
}
int eqlRowColCnt=0;
String colStr;
for (int cIdx=0; cIdx < arr[0].length; cIdx++) {
sb=new StringBuilder();
for (int rIdx=0; rIdx < arr.length; rIdx++) {
sb.append((Integer.valueOf(arr[rIdx][cIdx]).toString()));
sb.append("*");
}
colStr=sb.toString();
if (rows.containsKey(colStr)) {
eqlRowColCnt+=rows.get(colStr);
}
}
return eqlRowColCnt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |