Wordsearch puzzle method

527 views Asked by At

I'm coding a wordsearch puzzle and I need to write a helper method called isHorizontalSpaceFree().

The method should check whether (starting from aRow and aCol) there is enough free space to insert word into letterGrid(left to right). If there is enough space, the method should return true, otherwise it should return false.

I need the method to return an out of bounds exception if the word length exceeds the end of the array as well.

Here is my code so far

   public boolean isHorizontalSpaceFree(int aRow, int aCol, String word)
   {
      boolean result = true;
      if (aCol < NUMBER_COLS - word.length())
      {
        int i = aCol;
        while (aCol < NUMBER_COLS - word.length())
        {
          if (letterGrid[aRow][aCol] != BLANK_ELEMENT
              || aCol > NUMBER_COLS - word.length())
          {
            result = false;
          }
          aCol++;
        }
      }
      else
      {
        result = false;
      }
      return result;
    }

I hope it's not too far away.

2

There are 2 answers

2
Kingamajick On BEST ANSWER

Based on your code, I'm assuming you want the method to return true if:

  1. There are enough remaining columns between aCol and NUMBER_COL to fit the word
  2. Each of cells in aRow between aCol and aCol + word.length() are BLANK_ELEMENTs

Given the above, the following should work:

public boolean isHorizontalSpaceFree(final int aRow, final int aCol, final String word) {
    // Asserts that the word will fit in the remaining cells
    if(aCol + word.length() > NUMBER_COLS) {
        return false;
    }
    // Asserts that each cell in the row aRow between aCol and aCol+word.length() are empty
    char[] columns = letterGrid[aRow] // I've assume your grid is made up of chars
    for(int i = aCol; i < aCol + word.length(); i++) {
        if(columns[i] != BLANK_ELEMENT) {
            return false;
        }
    }
    // There is enough remaining blank cells to insert the word
    return true;
}

Edit: As mentioned in Andreas_D answer, this method shouldn't really be throwing an exception, rather returning just true and false.

1
Andreas Dolk On

You shouldn't throw an Exception if the word is to long, just because that is (probably) not an exceptional condition. You could simply return false, because a word, whose length exceeds a row length, won't fit, the answer to your question "isHorizontalSpaceFree ?" is false.

Consider exceptions for the case word == null or word.equals("") though:

if (word == null || word.equals("")) {
   // a null reference or an empty String are not allowed
   throw new IllegalArgumentException("Word must not be null or empty");
}
if (word.length() > NUMBER_COLS) {
   // a word that is longer then row does not fit (trivial case)
   return false;
}