Java wordsearch 字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21208997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:21:00  来源:igfitidea点击:

Java wordsearch Char arrays

javaarrayschar

提问by

I have been struggling with this wordsearch project for a couple of days now, just trying to get the horizontal search working. It's meant to work in all 8 possible directions (horizontal, vertical, diagonal). Here is my current code.

我已经在这个词搜索项目上苦苦挣扎了几天,只是想让水平搜索工作。它旨在在所有 8 个可能的方向(水平、垂直、对角线)上工作。这是我当前的代码。

For now I'm only worrying about the horizontal, as I suspect if I get the comparison down right then the rest will be simpler.

现在我只担心水平,因为我怀疑如果我正确地进行比较,那么其余的会更简单。

I am meant to write code which finds the words contained in the boards array, and output those characters to another array which is the same size as the board array (Hence, the output array is the solution to the board array).

我打算编写代码来查找板阵列中包含的单词,并将这些字符输出到另一个与板阵列大小相同的阵列(因此,输出阵列是板阵列的解决方案)。

So far, all my code does is iterate through the entire board, then check if it matches with the first character of the wordlist, if it does then this character is assigned on the output array, which is finally printed in the end out to the console for the user to see.

到目前为止,我的代码所做的就是遍历整个板子,然后检查它是否与单词列表的第一个字符匹配,如果匹配,则将该字符分配到输出数组上,最后将其打印到控制台供用户查看。

My question is, how can I forward my search to iterate the wordlist as well? Is my approach wrong? For example, if the board char matches with the char in the wordlist, then continue in that specified direction (in my case I'm worrying about the horizontal direction) and find the word.

我的问题是,我怎样才能转发我的搜索来迭代词表?我的方法错了吗?例如,如果 board char 与 wordlist 中的 char 匹配,则继续在该指定方向(在我的情况下我担心水平方向)并找到单词。

Also, method 'filter' is meant to handle exceptionOutofBounds in case the search goes off the board.

此外,方法 'filter' 旨在处理 exceptionOutofBounds,以防搜索不正常。

Any ideas or approaches are welcome.

欢迎任何想法或方法。

采纳答案by Garrett Openshaw

Here is an example of searching a grid for words in different direction. I have implemented three of them, and left three of them for you to finish. In my personal preference, I would have used an array of strings instead of a jagged array for the wordList, but I went with the OP's choice for the implementation. I made a simple version using a 4 x 4 grid, and a list of 3 words. Note that I call fillWithSpaces() on the output board. This is critical for formatting.

这是一个在网格中搜索不同方向单词的示例。我已经实现了其中的三个,剩下三个让你完成。根据我个人的喜好,我会为 wordList 使用字符串数组而不是锯齿状数组,但我选择了 OP 的实现。我使用 4 x 4 网格和 3 个单词的列表制作了一个简单版本。请注意,我在输出板上调用了 fillWithSpaces()。这对于格式化至关重要。

I have a text file called "board.txt"

我有一个名为“board.txt”的文本文件

dcat
aoiq
eigk
snur

and a text file "words.txt"

和一个文本文件“words.txt”

dog
cat
runs

Here is output of the program:

这是程序的输出:

DCAT
-O--
--G-
SNUR

My strategy is to search the board for the first letter of a word. Once I find it, I update the static fields foundRow and foundColumn. When I use a different word, I update the static field currentWord. When I find a letter that matches, I have six different methods, checkForwards() checkBackwards() and so on. (There are other ways to do this but I am trying to make the example as clear as possible.

我的策略是在黑板上搜索单词的第一个字母。一旦我找到它,我就会更新静态字段 foundRow 和 foundColumn。当我使用不同的词时,我会更新静态字段 currentWord。当我找到匹配的字母时,我有六种不同的方法,checkForwards() checkBackwards() 等等。(还有其他方法可以做到这一点,但我试图使示例尽可能清晰。

Here is the check backwards method. Since I already know the first letter matches, I start with the second (index 1). For each new char, I check that it will be on the board before I compare the values. (There is a better way to do this as well). If anything fails, I return. If all the chars match, I copy each char one at a time.

这是向后检查方法。因为我已经知道第一个字母匹配,所以我从第二个(索引 1)开始。对于每个新字符,在比较值之前,我会检查它是否会出现在板上。(也有更好的方法来做到这一点)。如果有任何失败,我会回来。如果所有字符都匹配,我一次复制一个字符。

static void checkBackwards()
{
    for(int i = 1; i < wordList[currentWord].length; i++)
    {
        if(foundColumn - i < 0) return;
        if(wordList[currentWord][i] != board[foundRow][foundColumn - i]) return;
    }
    //if we got to here, update the output
    for(int i = 0; i < wordList[currentWord].length; i++)
    {
        output[foundRow][foundColumn - i] = wordList[currentWord][i];
    }
    return;
}

And here is the source code:

这是源代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Wordsearch 
{
    static Scanner input;
    static char[][] wordList;
    static char[][] board;
    static char[][] output;

    static int foundRow;
    static int foundColumn;
    static int currentWord;

    public static void main(String[] args) throws FileNotFoundException
    {
        File wordInput = new File("words.txt");
        File boardInput = new File("board.txt");
        if(!wordInput.exists() || !boardInput.exists())
        {
            System.out.println("Files do not exist.");
            System.exit(1);
        }

        wordList = new char[3][];   //word list matrix 
        board = new char[4][4]; //board or grid matrix
        output= new char[4][4]; //solved puzzle 

        fillWithSpaces(output);

        input = new Scanner(wordInput);
        for(int i = 0; i < wordList.length; i++)
        {
            wordList[i] = input.nextLine().toUpperCase().toCharArray();
        }

        input = new Scanner(boardInput);
        for(int i = 0; i < board[0].length; i++)
        {
            board[i] = input.nextLine().toUpperCase().toCharArray();
        }

        for(int i = 0; i < wordList.length; i++)
        {
            currentWord = i;
            if(findFirstLetter())
            {
                checkEachDirection();
            }
        }

        print(output);
    }

    static boolean findFirstLetter()
    {
        for(int r = 0; r < board.length; r++)
        {
            for(int c = 0; c < board.length; c++)
            {
                if(wordList[currentWord][0] == board[r][c])
                {
                    foundRow = r;
                    foundColumn = c;
                    return true;
                }
            }
        }
        return false;
    }

    static void checkEachDirection()
    {
        checkForwards();
        checkBackwards();
        //checkUp();
        //checkDown();
        checkDiagonalDown();
        //checkDiagonalUp();
    }

    static void checkForwards()
    {
        for(int i = 1; i < wordList[currentWord].length; i++)
        {
            if(foundColumn + i > board.length - 1) return;
            if(wordList[currentWord][i] != board[foundRow][foundColumn + i]) return;
        }
        //if we got to here, update the output
        for(int i = 0; i < wordList[currentWord].length; i++)
        {
            output[foundRow][foundColumn + i] = wordList[currentWord][i];
        }
        return;
    }

    static void checkBackwards()
    {
        for(int i = 1; i < wordList[currentWord].length; i++)
        {
            if(foundColumn - i < 0) return;
            if(wordList[currentWord][i] != board[foundRow][foundColumn - i]) return;
        }
        //if we got to here, update the output
        for(int i = 0; i < wordList[currentWord].length; i++)
        {
            output[foundRow][foundColumn - i] = wordList[currentWord][i];
        }
        return;
    }

    static void checkDiagonalDown()
    {
        for(int i = 1; i < wordList[currentWord].length; i++)
        {
            if(foundColumn + i > board.length - 1) return;
            if(foundRow + i > board.length - 1) return;
            if(wordList[currentWord][i] != board[foundRow + i][foundColumn + i]) return;
        }
        //if we got to here, update the output
        for(int i = 0; i < wordList[currentWord].length; i++)
        {
            output[foundRow + i][foundColumn + i] = wordList[currentWord][i];
        }
        return;
    }

    static void print(char[][] board)
    {
        for(int i = 0; i < board.length; i++)
        {
            for(int j = 0; j < board.length; j++)
            {
                System.out.print(board[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }

    static void fillWithSpaces(char[][] board)
    {
        for(int i = 0; i < board.length; i++)
        {
            for(int j = 0; j < board.length; j++)
            {
                board[i][j] = '-';
            }
        }
    }
}

回答by jedwards

Consider the following program:

考虑以下程序:

import java.util.ArrayList;

public class WordSearch {

    static char[][] board;
    static int board_x, board_y;
    static ArrayList<String> search_words;

    public static void main(String args[])
    {
        board = new char[][]{
            { 's', 't', 'a', 'c', 'k' },
            { 'x', 'f', 'l', 'o', 'w' },
            { 'x', 'x', 'x', 'v', 'x' },
            { 'x', 'x', 'x', 'e', 'x' },
            { 'x', 'x', 'x', 'r', 'x' },
        };
        // You could also get these from board.size, etc
        board_x = 5;    
        board_y = 5;

        search_words = new ArrayList<String>();
        search_words.add("stack");
        search_words.add("over");
        search_words.add("flow");
        search_words.add("not");

        for(String word : search_words){
            find(word);
        }
    }

    public static void find(String word)
    {
        // Search for the word laid out horizontally
        for(int r=0; r<board_y; r++){
            for(int c=0; c<=(board_x - word.length()); c++){
                // The pair (r,c) will always be where we start checking from
                boolean match = true;
                for(int i=0; i<word.length(); i++){
                    if(board[r][c + i] != word.charAt(i)){
                        match = false;
                        System.out.format("    '%s' not found starting at (%d,%d) -- first failure at %d\n", word, r, c, i);
                        break;
                    }
                }

                if(match){
                    System.out.format("Found match (horizontal) for '%s' starting at (%d,%d)\n", word, r, c);
                }
            }
        }
    }
}

The board is a 2-dimensional char array and the list of words you're searching for is an ArrayList called search_words.

该板是一个二维字符数组,您要搜索的单词列表是一个名为 search_words 的 ArrayList。

After some simple sample initialization of the board and the search_wordslist, it iterates through the words in the list, searching for each if it lies horizontally.

在对板和search_words列表进行一些简单的示例初始化之后,它遍历列表中的单词,搜索每个单词是否水平。

This idea could be extended to search vertically or diagonally as well with some tweaks.

这个想法可以扩展到垂直或对角搜索以及一些调整。

The logic here is what you should take away from the sample program, not necessarily the structure. If I were doing this for anything serious, I'd probably have a Boardclass, probably with a .find(word)method.

这里的逻辑是你应该从示例程序中拿走的东西,不一定是结构。如果我是为了任何严肃的事情而这样做,我可能会有一个Board类,可能有一个.find(word)方法。

Finally, the verbose output is:

最后,详细的输出是:

Found match (horizontal) for 'stack' starting at (0,0)
    'stack' not found starting at (1,0) -- first failure at 0
    'stack' not found starting at (2,0) -- first failure at 0
    'stack' not found starting at (3,0) -- first failure at 0
    'stack' not found starting at (4,0) -- first failure at 0
    'over' not found starting at (0,0) -- first failure at 0
    'over' not found starting at (0,1) -- first failure at 0
    'over' not found starting at (1,0) -- first failure at 0
    'over' not found starting at (1,1) -- first failure at 0
    'over' not found starting at (2,0) -- first failure at 0
    'over' not found starting at (2,1) -- first failure at 0
    'over' not found starting at (3,0) -- first failure at 0
    'over' not found starting at (3,1) -- first failure at 0
    'over' not found starting at (4,0) -- first failure at 0
    'over' not found starting at (4,1) -- first failure at 0
    'flow' not found starting at (0,0) -- first failure at 0
    'flow' not found starting at (0,1) -- first failure at 0
    'flow' not found starting at (1,0) -- first failure at 0
Found match (horizontal) for 'flow' starting at (1,1)
    'flow' not found starting at (2,0) -- first failure at 0
    'flow' not found starting at (2,1) -- first failure at 0
    'flow' not found starting at (3,0) -- first failure at 0
    'flow' not found starting at (3,1) -- first failure at 0
    'flow' not found starting at (4,0) -- first failure at 0
    'flow' not found starting at (4,1) -- first failure at 0
    'not' not found starting at (0,0) -- first failure at 0
    'not' not found starting at (0,1) -- first failure at 0
    'not' not found starting at (0,2) -- first failure at 0
    'not' not found starting at (1,0) -- first failure at 0
    'not' not found starting at (1,1) -- first failure at 0
    'not' not found starting at (1,2) -- first failure at 0
    'not' not found starting at (2,0) -- first failure at 0
    'not' not found starting at (2,1) -- first failure at 0
    'not' not found starting at (2,2) -- first failure at 0
    'not' not found starting at (3,0) -- first failure at 0
    'not' not found starting at (3,1) -- first failure at 0
    'not' not found starting at (3,2) -- first failure at 0
    'not' not found starting at (4,0) -- first failure at 0
    'not' not found starting at (4,1) -- first failure at 0
    'not' not found starting at (4,2) -- first failure at 0

回答by Abdul Khan

you can try this for horizontal search String word = ""; for (String keyWord : words) {

你可以试试这个进行水平搜索 String word = ""; 对于(字符串关键字:单词){

        // STEP1: Find *************IF ******************* The word is in
        // the Array
        // CODE HERE
        boolean found = false;
        for (int i = 0; i < puzzle.length; i++) {
            String rowString = "";
            for (int j = 0; j < puzzle[i].length; j++) {
                rowString += puzzle[i][j];
                if (rowString.contains(keyWord) && !found) {

                    System.out.println(keyWord);
                    int index = rowString.indexOf(keyWord);
                    rowString.indexOf(keyWord);
                    // int length = keyWord.length();
                    for (int ii = 0; ii < keyWord.length(); ii++) {
                        solutionArray[i][index + ii] = keyWord.charAt(ii);
                        rowString += puzzle[i][j];
                        System.out.println();
                        // length--;
                    }
                    found = true;
                }

            }
        }