I'm working on problem where I have to check if all 9 digits are in 3x3 matrix.
I know that I should loop over the 3x3 matrix and check for each number is digit or not. Here is my code, but I don't have directions to do it.
public boolean find(int num) {
int []a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < a.length; i++)
if (a[i] == num)
return true;
return false;
}
public boolean allDigit() {
boolean isDigit = true;
for (int i = 0; i< _3x3.length; i++) {
for(int j = 0; j < _3x3[i].length; j++) {
if (!find(_3x3[i][j]))
isDigit = false;
}
}
}
The presented code contains several typos:
num
parameter in find
has to be int
allDigit
should return isDigit
in the end_3x3
needs to be defined and populated somewhere, or passed to allDigit
as an argument. After fixing the mentioned issues the code should detect if all the numbers in _3x3
array belong to the closed range [1, 9]
, that is, if the input matrix contains 1
in all its cells, the code returns true
.
However, if the purpose of the task is to check that the input matrix contains all digits , that is, there is no duplicate entry, then the separate find
method should not be called. Instead a boolean array is needed to check for duplicate entries:
public boolean allDigitsPresent(int[][] arr) {
boolean[] digitSet = new boolean[10];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int d = arr[i][j]; // digit
if (d <= 0 || d >= digitSet.length) {
return false; // invalid value in the matrix
}
if (digitSet[d]) { // already set, duplicate is found
return false;
}
digitSet[d] = true;
}
}
return true; // no duplicate digit is found, all digits are in range [1..9]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.