Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
173 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...