In: Computer Science
IN JAVA!
Lab 13 Problem 4 (name this Lab13_Problem4)
SHORT SUMMARY:
SOURCE CODE:
public class Duplicate2DArray {
public static void main(String[] args) {
// TEST CASE 1 - No duplicates
System.out.println("\nTEST CASE 1");
int iVals[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 10, 12}, {9, 10, 11, 12}, {1, 27, 3, 4}};
fvDisplay(iVals);
boolean bDups = fbDupRows(iVals);
if (bDups) {
System.out.println("\nDuplicate Rows Found");
} else {
System.out.println("\nNo Duplicate Rows Found");
}
// TEST CASE 2 - Adjacent Rows identical - 1st and 2nd Row duplicate value
System.out.println("\nTEST CASE 2");
int iVals1[][] = {{1, 2, 3, 4}, {1, 2, 3, 4}, {9, 10, 10, 12}, {9, 10, 11, 12}, {1, 27, 3, 4}};
boolean bDups1 = fbDupRows(iVals1);
fvDisplay(iVals1);
if (bDups1) {
System.out.println("\nDuplicate Rows Found");
} else {
System.out.println("\nNo Duplicate Rows Found");
}
// TEST CASE 3 - 2nd and 4th rows same value
System.out.println("\nTEST CASE 3");
int iVals2[][] = {{1, 2, 3, 4}, {5, 6,7, 8}, {9, 10, 10, 12}, {5, 6, 7, 8}, {1, 27, 3, 4}};
boolean bDups2 = fbDupRows(iVals2);
fvDisplay(iVals2);
if (bDups2) {
System.out.println("\nDuplicate Rows Found");
} else {
System.out.println("\nNo Duplicate Rows Found");
}
}
// Display array with 6 horizontal space
private static void fvDisplay(int[][] iVals) {
// iterating through rows
for (int row = 0; row < iVals.length; row++) {
// iterating through columns
for (int column = 0; column < iVals[row].length; column++) {
// Display array values with horizontal space of 6
System.out.printf("%6d", iVals[row][column]);
}
System.out.println("");
}
}
// checks whether there are duplicate rows
private static boolean fbDupRows(int[][] iVals) {
// iterating through rows
for (int row1 = 0; row1 < iVals.length; row1++) {
// iterating from next rows
for (int row2 = row1 + 1; row2 < iVals.length; row2++) {
// counter variable
int dupCount = 0;
// iterating through the column
for (int column = 0; column < iVals[row1].length; column++) {
// check the values are equal
if (iVals[row1][column] == iVals[row2][column]) {
// increment the counter variable
dupCount++;
}
}
// if the counter variable value equals to column duplicate found
if (dupCount == iVals[row1].length) {
return true;
}
}
}
// when no duplicates found
return false;
}
}
CODE SCREENSHOT:
SAMPLE OUTPUT:
******************************************************************************
Feel free to rate the answer and comment your questions, if you have any.
Please upvote the answer and appreciate our time.
Happy Studying!!!
******************************************************************************