Моему классу недавно была назначена программа, в которой нам нужно создать кроссворд, используя двумерный массив, а также рекурсию.Инструкции следующие:
*** Напишите программу, которая читает слова из входного файла words.txt, создавая отображение кроссворда, максимизируя перекрывающиеся буквы между словами.Предположим, что на доске 15 строк и 15 столбцов.
Первая строка входного файла - это `` число, представляющее, сколько слов присутствует.Затем предоставляются слова, по одному в строке.Когда ваша программа запускается, она должна отображать найденные решения, а также количество совпадений для каждого из них.В конце он должен отобразить решение с максимальным количеством найденных совпадений или сообщение, если кроссворд невозможен. *
У меня куча проблем, заставляющих задуматьсяэта концепция.Я понимаю необходимость встроенных циклов for для рекурсии, но я не уверен, куда идти дальше.Ниже приведен пример кода, который поможет нам начать работу:
/* Dictionary.java
* Read in words from a file. The first line in the file should
* be the number of words. Subsequent lines have the words
* themselves, one per line. For instance, a sample file
* could contain:
* 5
* Java
* Programming
* Euphoria
* Consternation
* Education
*
* This sample code is not meant to be stand-alone, but rather
* is meant for you to copy and paste into some other class.
*/
//the following are needed to implement reading from the file
import java.io.*; // Used for IOException, File
import java.util.Scanner; // Used for File input
public class ReadWords
{
// Declare an array of strings to hold the words
String[] wordsArray;
// chain off to another method to avoid static errors
public static void main( String[] args)
{
ReadWords theInstance = new ReadWords();
theInstance.doIt();
}
// ------------------------------------------------------------------------
// Read in the words
void doIt()
{ // Use a try-catch block for exception handling. What this does is
// provide a place in your program to handle potential file read errors
try {
// Define a Scanner to read from an input file. Note that the name of
// the file given in the code below MUST match the actual filename of
// the words file. This file should be in the same directory
// as the source code for this project
File wordsFile = new File("words.txt"); // declare the file
// Ensure file exists and is in the correct directory
if( ! wordsFile.exists()) {
System.out.println("*** Error *** \n" +
"Your words file has the wrong name or is " +
"in the wrong directory. \n" +
"It should be in " + System.getProperty("user.dir") + "\n" +
"\n" +
"Aborting program...\n\n");
System.exit( -1); // Terminate the program
}
Scanner inputFile = new Scanner( wordsFile);
// while there are words in the input file, add them to the dictionary
int numberOfWords = inputFile.nextInt();
// use this value to allocate memory for the words array
wordsArray = new String[ numberOfWords];
// Now read this many words
for( int i=0; i< wordsArray.length; i++) {
// read next word and store into array
wordsArray[ i] = inputFile.next().toUpperCase();
}
}
catch (IOException e)
{
System.out.println("Error in words file read");
System.exit( -1);
}
// echo the words found
System.out.println("The words read are: ");
for( int i=0; i< wordsArray.length; i++) {
System.out.println( wordsArray[ i]);
}
}//end doIt()
}//end class
Если у кого-то есть какие-либо предложения или рекомендации относительно того, куда это следует направить, это будет очень полезно.