I need to fix three bugs in this code without drastic modifications. I thinkg th
ID: 3876005 • Letter: I
Question
I need to fix three bugs in this code without drastic modifications. I thinkg that the iteration over every element in 2D array should be
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; i++)
instead of provided code, but I don't get the other problems. Please help.
Here is the provided code.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Debugging{
public static void setHints(int[][] array){
for(int i = 0; i < array.length + 1; i++) {
for(int j = 0; j < array.length + 1; j++) {
if(array[i][j] == -1) {
int rowModifier = -1;
int columnModifier = -1;
while(rowModifier <= 1 && columnModifier <= 1) {
int rowIndex = i + rowModifier;
int columnIndex = j + columnModifier;
if(!(rowModifier == 0 && columnModifier == 0) && (isValidIndex(rowIndex,columnIndex,array) == true)) {
array[rowIndex][columnIndex] = 1;
}
if(columnModifier < 1) {
columnModifier++;
}
else {
columnModifier = -1;
rowModifier++;
}
}
}
}
}
}
public static boolean isValidIndex(int rowIndex, int columnIndex, int[][] anArray) {
boolean toReturn = false;
if((rowIndex < 0) || (columnIndex < 0)){
toReturn = false;
}
else if(rowIndex >= anArray.length) {
toReturn = false;
}
else if(columnIndex >= anArray[rowIndex].length) {
toReturn = false;
}
else if(anArray[rowIndex][columnIndex] == -1) {
toReturn = false;
}
return toReturn;
}
}
Explanation / Answer
public class Debugging{
public static void setHints(int[][] array){
// 1. you already found it
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
if(array[i][j] == -1) {
int rowModifier = -1;
int columnModifier = -1;
while(rowModifier <= 1 && columnModifier <= 1) {
int rowIndex = i + rowModifier;
int columnIndex = j + columnModifier;
if(!(rowModifier == 0 && columnModifier == 0) && (isValidIndex(rowIndex,columnIndex,array) == true)) {
array[rowIndex][columnIndex] = 1;
}
if(columnModifier < 1) {
columnModifier++;
}
else {
columnModifier = -1;
rowModifier++;
}
}
}
}
}
}
public static boolean isValidIndex(int rowIndex, int columnIndex, int[][] anArray) {
//2. toReturn has to be true generally and if any of the conditions failed, then it will be changed to false
boolean toReturn = true;
if((rowIndex < 0) || (columnIndex < 0)){
toReturn = false;
}
// 3. rowIndex should be 1 less than the length since it starts with 0
else if(rowIndex > anArray.length) {
toReturn = false;
}
// column Index should be 1 less than the length since it starts with 0
else if(columnIndex > anArray[rowIndex].length) {
toReturn = false;
}
else if(anArray[rowIndex][columnIndex] == -1) {
toReturn = false;
}
return toReturn;
}
}