随机将列表中的字符串逐个字符放置到2D数组中

时间:2019-04-17 17:42:56

标签: java arrays list loops multidimensional-array

我正在尝试将PuzzleWords或userSpecifiedWords列表中的每个单词随机放置到Puzzle 2D数组中。可以将单词上下垂直放置,上下垂直放置,左右水平放置以及左右水平放置。本质上就是搜索单词。但是似乎无法弄清楚如何将下一个字符放置在正确的位置,从而满足这些要求。

我尝试首先在2d数组中生成一个随机位置,然后将第一个单词的第一个字符放置到该位置,但是要与下一个字符的放置作斗争,然后再移动到下一个单词。

//Initialising the 2d array and list of words.

public class WordSearchPuzzle {
    private char [][] puzzle;
    private List<String> puzzleWords;

//What I have so far to take the word out of the array, generate a random pos in 2d array then check if the pos is empty, if empty place the first char of word in that pos else generate new pos.

for (int i = 0; i < puzzleWords.size(); i++) {
            for (int r = 0; r < puzzle.length; r++) {
                for (int c = 0; c < puzzle[r].length; c++) {
                    String s = puzzleWords.get(i);
                    int wordLength = s.length();
                    char firstChar = s.charAt(0);
                    while(puzzle[rowGenerate][colGenerate] != ' ') {
                        puzzle[rowGenerate][colGenerate] = puzzle[(int) Math.random() * gridSize + 1][(int) Math.random() * gridSize + 1];
                    }
                    puzzle[rowGenerate][colGenerate] = firstChar;
                }

0 个答案:

没有答案