用这种格式打印出2-d数组

时间:2017-09-20 17:20:07

标签: java arrays

我正在寻找二维数组中的单词,我得到了搜索作品(垂直,水平和对角线)

我只是无法以这种特定格式打印找到的单词。就像它打印实际上在2D数组中找到它的单词。 我希望我的想法很明确

代码从file.txt读取Charters并将它们保存到2d数组中。 我们在这个数组中搜索一个单词。

并尝试按照他们所在的顺序找到它们。 我附上了一个例子

   Puzzle          word file       Output
n o h t y p s      ruby
m i a r y c c      cave          c
l l e k s a h                      a
r u b y v m e                r u b y v
e h h e l l m                          e
p c j n i c e
r e e k b i p

这是代码......

import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

public class WordPuzzle {

    // to print..
    private Set<Point> wordPoints = new HashSet<>();




    public Set<String> findWords(char[][] puzzle, String[] inputWords) {
        Set<String> foundWords = new HashSet<String>();
        int minimumWordLength = findMinimumWordLength(inputWords);
        Set<String> possibleWords = findPossibleWords(puzzle, minimumWordLength);
        for(String word : inputWords) {
            for(String possibleWord : possibleWords) {
                if(possibleWord.contains(word) || possibleWord.contains(new StringBuffer(word).reverse())) {
                    foundWords.add(word);
                    break;
                }
            }
        }       
        return foundWords;
    }

    private int findMinimumWordLength(String[] inputWords) {
        int minimumLength = Integer.MAX_VALUE;
        for(String word : inputWords) {
            if(word.length() < minimumLength)
                minimumLength = word.length();
        }
        return minimumLength;
    }

    private Set<String> findPossibleWords(char[][] puzzle, int minimumWordLength) {
        Set<String> possibleWords = new LinkedHashSet<String>();
        int dimension = puzzle.length; //Assuming puzzle is square
        if(dimension >= minimumWordLength) {
            /* Every row in the puzzle is added as a possible word holder */
            for(int i = 0; i < dimension; i++) {
                if(puzzle[i].length >= minimumWordLength) {
                    possibleWords.add(new String(puzzle[i]));
                }
            }
            /* Every column in the puzzle is added as a possible word holder */
            for(int i = 0; i < dimension; i++) {
                StringBuffer temp = new StringBuffer();
                for(int j = 0; j < dimension; j++) {
                    temp = temp.append(puzzle[j][i]);
                }
                possibleWords.add(new String(temp));
            }
            /* Adding principle diagonal word holders */
            StringBuffer temp1 = new StringBuffer();
            StringBuffer temp2 = new StringBuffer();
            for(int i = 0; i < dimension; i++) {
                temp1 = temp1.append(puzzle[i][i]);
                temp2 = temp2.append(puzzle[i][dimension - i - 1]);
            }
            possibleWords.add(new String(temp1));
            possibleWords.add(new String(temp2));
            /* Adding non-principle diagonal word holders */
            for(int i = 1; i < dimension - minimumWordLength; i++) {
                temp1 = new StringBuffer();
                temp2 = new StringBuffer();
                StringBuffer temp3 = new StringBuffer();
                StringBuffer temp4 = new StringBuffer();
                for(int j = i, k = 0; j < dimension && k < dimension; j++, k++) {
                    temp1 = temp1.append(puzzle[j][k]);
                    temp2 = temp2.append(puzzle[k][j]);
                    temp3 = temp3.append(puzzle[dimension - j - 1][k]);
                    temp4 = temp4.append(puzzle[dimension - k - 1][j]);
                }
                possibleWords.add(new String(temp1));
                possibleWords.add(new String(temp2));
                possibleWords.add(new String(temp3));
                possibleWords.add(new String(temp4));
            }
        }
        return possibleWords;
    }

    public static void main(String args[]) throws FileNotFoundException {
        WordPuzzle program = new WordPuzzle();
        ////////////////////////////////////////// if you want to copy the word file, copy here. //////
     // allocate the file..
     File inFile = new File("C:\\Users\\admin\\Desktop\\workspace\\DS600\\src\\Puzzle.txt");    
     // scan the file..
        Scanner scanner = new Scanner(inFile); 
    // create an array of type char
        char[][] puzzleInput = new char[50][50];    
    //assign every letter in the char array
        for(int i=0; i < 50; i++) {
            puzzleInput[i] = scanner.nextLine().toCharArray();
        }

        scanner.close();
      ////////////////////////// end the copy file here. //////////////////////////

        String[] InputWords = {"ONE", "TWO","THREE","POLAND"};      
        Set<String> wordsFound = program.findWords(puzzleInput, InputWords);


        // PRINT OUT... ONLY
        for (int y = 0; y < puzzleInput.length; y++) {
            for (int x = 0; x < puzzleInput[y].length; x++) {

                // HOW TO PRINT IT .. ??

            }
            System.out.println();
        }

    /*    
        for(String word : wordsFound) {
            System.out.println(word);
        }
        */

    }

}

3 个答案:

答案 0 :(得分:0)

你可以做的是有一个第二个数组,它只是空的,但与第一个数组的尺寸相同,每次在第一个数组中找到一个单词时,你都会按顺序将单词中的所有字母添加到第二个数组中第一个。因此,例如,一旦您查看第一个数组并在某个位置找到“ruby”,请将“ruby”添加到第二个数组的相同位置。这样,您将所有找到的单词添加到空数组中,从而生成一个只包含您在完全相同位置找到的单词的数组。

答案 1 :(得分:0)

这是我在编码竞赛中解决类似问题时编写的工作代码示例。它在2-D char数组中找到单词并用坐标打印出来。希望这会有所帮助......

public class Solution {
    public static void main(String[] args) {
        char[][] crossword = new char[][]{
                {'f', 'd', 'e', 'r', 'l', 'k'},
                {'u', 's', 'a', 'm', 'e', 'o'},
                {'l', 'n', 'g', 'r', 'o', 'v'},
                {'m', 'l', 'p', 'r', 'r', 'h'},
                {'p', 'o', 'e', 'e', 'j', 'j'}
        };
        List<Word> allWords = detectAllWords(crossword, "home", "same");
        for(Word word : allWords) {
            System.out.println(word.toString());
        }
        /*
        Expected result:
        home - (5, 3) - (2, 0)
        same - (1, 1) - (4, 1)
        */
    }

    public static List<Word> detectAllWords(char[][] crossword, String... words) {

        List<Word> wordList = new ArrayList<>();
        int[][] searchDirections = new int[][] {
                {0, 1},
                {1, 1},
                {1, 0},
                {1, -1},
                {0, -1},
                {-1, -1},
                {-1, 0},
                {-1, 1},
        };
        for (String word : words) nextWord:{
            for (int i = 0; i < crossword.length; i++) {
                for (int j = 0; j < crossword[i].length; j++) {
                    if (word.charAt(0) == crossword[i][j]) {
                        for (int directions = 0; directions < searchDirections.length; directions++) {
                            int tmp_i = i, tmp_j = j, wordPos = 1;
                            while (wordPos < word.length()) {
                                tmp_i += searchDirections[directions][0];
                                tmp_j += searchDirections[directions][1];
                                if (tmp_i < 0 || tmp_i >= crossword.length || tmp_j < 0 || tmp_j >= crossword[tmp_i].length)
                                    break;
                                if (word.charAt(wordPos) != crossword[tmp_i][tmp_j])
                                    break;
                                else if (wordPos == word.length() - 1) {
                                    Word tWord = new Word(word);
                                    tWord.setStartPoint(j, i);
                                    tWord.setEndPoint(tmp_j, tmp_i);
                                    wordList.add(tWord);
                                    break nextWord;
                                }
                                wordPos++;
                            }
                        }
                    }
                }
            }
        }
        return wordList;
    }

    public static class Word {
        private String text;
        private int startX;
        private int startY;
        private int endX;
        private int endY;

        public Word(String text) {
            this.text = text;
        }

        public void setStartPoint(int i, int j) {
            startX = i;
            startY = j;
        }

        public void setEndPoint(int i, int j) {
            endX = i;
            endY = j;
        }

        @Override
        public String toString() {
            return String.format("%s - (%d, %d) - (%d, %d)", text, startX, startY, endX, endY);
        }
    }
}

答案 2 :(得分:0)

除了我原来的答案,这里是您完全需要的完整代码。请注意print2DArray(...)静态方法,该方法执行将找到的单词打印在与原始数组内相同位置的所有工作:

public class Solution {
    public static void main(String[] args) {
        char[][] crossword = new char[][]{
                {'f', 'd', 'e', 'r', 'l', 'k'},
                {'u', 's', 'a', 'm', 'e', 'o'},
                {'l', 'n', 'g', 'r', 'o', 'v'},
                {'m', 'l', 'p', 'r', 'r', 'h'},
                {'p', 'o', 'e', 'e', 'j', 'j'}
        };
        List<Word> allWords = detectAllWords(crossword, "home", "same");
        // Print the results with starting and ending coordinates:
        for(Word word : allWords) {
            System.out.println(word.toString());
        }
        // Print the results as they are inside the original array
        print2DArray(allWords, crossword);
    }

    public static void print2DArray(List<Word> words, char[][] array) {

        char[][] toPrint = new char[array.length][array[0].length];

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                toPrint[i][j] = '#';
            }
        }

        for(Word word : words) {

            int vectorX = word.endX - word.startX;
            int vectorY = word.endY - word.startY;

            if(vectorX > 0) {
                vectorX = 1;
            } else if(vectorX < 0) {
                vectorX = -1;
            }

            if(vectorY > 0) {
                vectorY = 1;
            } else if(vectorY < 0) {
                vectorY = -1;
            }

            for(int i = 0; i < word.text.length(); i++) {
                toPrint[word.startY + (i * vectorY)][word.startX + (i * vectorX)] = word.text.charAt(i);
            }
        }


        for (int i = 0; i < toPrint.length; i++) {
            for (int j = 0; j < toPrint[i].length; j++) {
                if(toPrint[i][j] == '#') {
                    if(j == toPrint[i].length -1) {
                        System.out.println("  ");
                    } else {
                        System.out.print("  ");
                    }
                } else {
                    if(j == toPrint[i].length -1) {
                        System.out.println(" " + toPrint[i][j]);
                    } else {
                        System.out.print(" " + toPrint[i][j]);
                    }
                }
            }
        }
    }

    public static List<Word> detectAllWords(char[][] crossword, String... words) {

        List<Word> wordList = new ArrayList<>();
        int[][] searchDirections = new int[][]{
                {0, 1},
                {1, 1},
                {1, 0},
                {1, -1},
                {0, -1},
                {-1, -1},
                {-1, 0},
                {-1, 1},
        };
        for (String word : words)
            nextWord:{
                for (int i = 0; i < crossword.length; i++) {
                    for (int j = 0; j < crossword[i].length; j++) {
                        if (word.charAt(0) == crossword[i][j]) {
                            for (int directions = 0; directions < searchDirections.length; directions++) {
                                int tmp_i = i, tmp_j = j, wordPos = 1;
                                while (wordPos < word.length()) {
                                    tmp_i += searchDirections[directions][0];
                                    tmp_j += searchDirections[directions][1];
                                    if (tmp_i < 0 || tmp_i >= crossword.length || tmp_j < 0 || tmp_j >= crossword[tmp_i].length)
                                        break;
                                    if (word.charAt(wordPos) != crossword[tmp_i][tmp_j])
                                        break;
                                    else if (wordPos == word.length() - 1) {
                                        Word tWord = new Word(word);
                                        tWord.setStartPoint(j, i);
                                        tWord.setEndPoint(tmp_j, tmp_i);
                                        wordList.add(tWord);
                                        break nextWord;
                                    }
                                    wordPos++;
                                }
                            }
                        }
                    }
                }
            }
        return wordList;
    }

    public static class Word {
        private String text;
        private int startX;
        private int startY;
        private int endX;
        private int endY;

        public Word(String text) {
            this.text = text;
        }

        public void setStartPoint(int i, int j) {
            startX = i;
            startY = j;
        }

        public void setEndPoint(int i, int j) {
            endX = i;
            endY = j;
        }

        @Override
        public String toString() {
            return String.format("%s - (%d, %d) - (%d, %d)", text, startX, startY, endX, endY);
        }
    }
}