3

This is what I have. The method should output an array of all available numbers in that space. For some reason, this doesn't filter out for the same box/row/col. How should it be coded properly?

  public int[] getAllowedValues(int row, int col){//both
    int[] allowedValues = new int[9];
    for(int i = 0; i < 9; i++){
      allowedValues[i] = i;
    }
    for(int i = 0; i < 9; i++){
      if(!(board[i][col] == 0)){
        allowedValues[board[i][col]] = 0; //anything with a 0 is illegal, with number means that number is legal
      }
      if(!(board[row][i] == 0)){
        allowedValues[board[row][i]] = 0; //anything with a 0 is illegal, with number means that number is legal
      }
    }
    int rowStart = 0; //rowStart is the top left coord of box the number is in
    if(row <= 3){ 
      rowStart = 1;
    } else if (row <= 6){
      rowStart = 4;
    } else if (row <= 9){
      rowStart = 7;
    }
    int colStart = 0; //colStart is the top left coord of the box the number is in
    if(col <= 3){
     colStart = 1;
    } else if (col <= 6){
     colStart = 4;
    } else if (col <= 9){
     colStart = 7;
    }
    for(int i = rowStart; i < rowStart + 3; i++){
      for(int j = colStart; j < colStart + 3; j++){
        if(!(board[i-1][j-1] == 0)){
          allowedValues[board[i-1][j-1]] = 0;
        }
      }
    }
    for(int i = row; i < 9; i++){
      for(int j = col; j < 9; j++){
        if((board[i][j] == 0)){
          allowedValues[board[i][j]] = 0;
        }
        if((board[j][i] == 0)){
          allowedValues[board[j][i]] = 0;
        }
      }
    }
    return allowedValues;
  }

1 Answers1

0

I'm going to give you steps on how to code this.

  1. Import ArrayList

  2. Create an ArrayList that has the values 1 through 9

  3. For each number that is in the row, column or 3 by 3 square (and therefore is not an allowed value), use the following code:

//x is a number in the row/column/square and al is the ArrayList
if(al.contains(x))al.remove(al.indexOf(x));
  1. Change the method type from int[] to ArrayList

  2. Return the ArrayList

If you have any difficulty or need help let me know.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459