简体   繁体   中英

Place a word in a 2d array

is there a way to place a word in a 2d array in a specific position? For example,i want to give the word, choose vertical or horizontal and the position ((3,3) or (3,4) or (5,6) etc) and the word will be placed in that position.This is my code for the array...

char [][] Board = new char [16][16];


    for (int i = 1; i<Board.length; i++) {
        if (i != 1) {
            System.out.println("\t");
            System.out.print(i-1);
        }

        for (int j = 1; j <Board.length; j++) {
            if ((j == 8 && i == 8) ||(j ==9 && i == 9) ||(j == 10 && i == 10) ||(j == 2        && i == 2) )
            {
                Board[i][j] = '*';
                System.out.print(Board[i][j]);
            }
            else {
                if (i == 1) {
                    System.out.print("\t");
                    System.out.print(j-1);
                }
                else {
                   Board[i][j] = '_';
                    System.out.print("\t");
                    System.out.print(""+Board[i][j]);
}

}

(the * means that the word cant be placed there)

Is there a way to place a word in a 2d array in a specific position?

Yes you can implement that. The pseudo-code is something like this:

public void placeWordHorizontally(char[][] board, String word, int x, int y) {
    for (int i = 0; i < word.length(); i++) {
        if (y + i >= board[x].length) {
             // fail ... edge of board
        } else if (board[x][y + i]) == '*') {
             // fail ... blocked.
        } else {
             board[x][y + i] = word.charAt(i);
        }
    }
}

and to do the vertical case you add i etcetera to the x position.

I won't give you the exact code because you'll learn more if you fill in the details yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM