Search code examples
javasearchmultidimensional-arraytraversal

I am trying to search my java multidimensional array from top left to bottom right going in a vertical pattern. What is wrong with the code I have?


I am trying to search my multidimensional array that is a 6x8 grid from top left to bottom right in a vertical pattern for a word, but I can't figure out what's wrong with my code. Can someone tell me what I'm doing wrong?

      public static String findTopToBottom (char[][]board, String word) {
        char[] letters = word.toCharArray();

        for (int i = 0; i <= board[i].length; i++) {
            for (int j = 0; j <= board.length; j++) {
                boolean found = true;

                for (int k = 0; k < letters.length; k++) {
                    if ((i + k > board[j].length) || (letters[k] != board[j][i+k])) {
                        found = false;
                        break;
                    }
                }

                if (found) {
                    return "String " + word + " found in row=" + i + " col=" +j;
                }
            }
        }
        return "String " + word + " not found";
    }

Solution

  • if ((i + k > board[j].length) || (letters[k] != board[j][i+k])) {
    

    will throw an out-of-bounds exception if i + k is equal to board[j].length, since indexes only go from 0 to .length - 1. Use >= instead of >.

    For the same reason, <= in the following need to be changed to <:

        for (int i = 0; i <= board[i].length; i++) {
            for (int j = 0; j <= board.length; j++) {
    

    since the maximum possible index will be .length - 1.

    And this:

        for (int i = 0; i <= board[i].length; i++) {
    

    just looks wrong, even after changing <= to <. The i index is supposed be the index of a column in the array, but when you say board[i].length you are treating i as a row index. This will not cause a problem for a 6x8 array, but it will for an 8x6 array, say, because you want i to go from 0 to 7, but when i=6, board[6].length will be out of bounds. If you're certain that all of the rows are the same length, you should change this to

        for (int i = 0; i < board[0].length; i++) {