Firstly, this is not homework;). I am trying to create a dictionary game from scratch and hit the barrier. I need some guidance.
I am using a 2d character array for a dictionary search grid. I find it very convenient to place words horizontally in these arrays, but I really got stuck on ideas on how to do this vertically.
This is what I have so far, you should just copy / paste it and run it
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"); } }
What prints something like ...
monkey?????? cow????????? elephant???? kangaroo???? ???????????? ???????????? ???????????? ???????????? ???????????? ???????????? ???????????? ????????????
I need to randomly lay them on the left / right side, but I can do it myself.
Question What is an efficient way to put words vertically in a 2d array as above? My initial thought was to count down for the required word length, break if something other than a is found ? , and continue to do so until I find a place for the word. However, this does not turn out beautiful, given the coincidence of words.
Any pointers?
java arrays multidimensional-array
Jimmy
source share