首先,這不是功課;)。我試圖從頭開始創建一個wordsearch遊戲,並且遇到了障礙,我需要一些指導。什麼是垂直遍歷二維數組的有效方法,以編程方式查找「空」集?
我正在使用一個字符的2d數組來爲wordsearch的網格。我很自然地將這些單詞放在這些數組中,但是我非常想知道如何垂直執行此操作。
這是我到目前爲止,你就應該能夠複製/粘貼並運行它
import java.util.ArrayList;
import java.util.List;
public class WordGame
{
private static List<String> words = new ArrayList<String>();
private static int longestWordLength = 0;
private static int padSize = 4;
private static char[][] grid = null;
public static void main(String[] args)
{
initialiseWords();
workOutLongestWord();
setupGrid();
printIt();
}
private static void printIt()
{
for (int i = 0; i < grid.length; i++)
{
for (int j = 0; j < grid.length; j++)
{
System.out.print(grid[i][j]);
}
System.out.print("\n");
}
}
private static void setupGrid()
{
grid = new char[longestWordLength + padSize][longestWordLength + padSize];
for (int i = 0; i < grid.length; i++)
{
String w = (i >= words.size()) ? "?" : words.get(i);
for (int j = 0; j < grid.length; j++)
{
grid[i][j] = (j >= w.length()) ? '?' : w.charAt(j);
}
}
}
private static void workOutLongestWord()
{
for (String word : words)
{
if (word.length() > longestWordLength)
{
longestWordLength = word.length();
}
}
}
private static void initialiseWords()
{
words.add("monkey");
words.add("cow");
words.add("elephant");
words.add("kangaroo");
}
}
打印出類似...
monkey??????
cow?????????
elephant????
kangaroo????
????????????
????????????
????????????
????????????
????????????
????????????
????????????
????????????
我需要隨機將它們放在左側/右側,但我可以自己做。
問題:試圖將單詞垂直放置到如上所述的二維數組中的有效方法是什麼?我最初的想法是要求向下計算所需的字長,如果發現除?
以外的任何內容,則打破它,並繼續這樣做直到我能找到該字的空間。但是,一旦我考慮到單詞重疊,這種情況並不會很好。
任何指針?