C ++ Wordsearch Puzzle Grid 2D Array

У меня проблема с чтением в текстовом файле (ниже), который содержит буквы для поиска слова. Я хочу прочитать текстовый файл в виде массива, а затем быть в состоянии сопоставить слова из моего dictionary.txt к wordsearch_grid.txt. Есть идеи?

wordsearch_grid:
9
E M M A R G O R P
C L U A U N L L D
O T A O F I L O I
M E U N J G E O K
P W H K G G H P Q
I C O M P U T E R
L L V R Z B A O X
E H O M L E Q G U
T N I R P D C O E

dictionary:
COMPILE
COMPUTER
DEBUGGING
HELLO
KITCHEN
GRAPHICS
LOOP
SPAN
PROGRAMME
WORLD

Код, который у меня есть, выглядит следующим образом:

#include "WordSearch.h"#include "fstream"#include <iostream>
#include <string>
#include "vector"

using namespace std;

vector<string> list;
vector<string> grid;
string line;
string n;

WordSearch::WordSearch(const char * const filename)
{}

WordSearch::~WordSearch()
{

}

void WordSearch::ReadSimplePuzzle() {

ifstream inFile;
inFile.open("wordsearch_grid.txt");

if (inFile.fail())
{
cerr << "Error Wordsearch Grid File" << endl;
exit(1);
}
else
{

while (getline (inFile, n))
{
cout << n << endl;
}
//grid[4][3];
inFile.close();
//cout << grid << endl;
cout << "\n" << endl;
}

}

void WordSearch::ReadSimpleDictionary()
{
ifstream inFile;
inFile.open("dictionary.txt");if (inFile.fail())
{
cerr << "Error Dictionary File" << endl;
exit(1);

}
else
{
int count = 0;
while (getline(inFile, line))
{
list.push_back(line);
cout << line << endl;
}
inFile.close();
}}

void WordSearch::SolvePuzzleSimple()

{}

До сих пор он может читать файлы и отображать их, но я хочу иметь возможность манипулировать сеткой так, чтобы я мог сопоставить первую и последнюю букву, скажем, «COMPILE», чтобы она соответствовала двум буквам в сетке, и выводить на выход .txt «COMPILE был найден в [1] [2]

0

Решение

Вот встроенная логика, которую вы можете инкапсулировать в своем классе по своему выбору:

#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
using namespace std;

ifstream inFile("wordsearch_grid.txt");
ifstream dict("dictionary.txt");
ofstream out("output.txt");

int main(){
string word;
char c;
char grid[9][9] = {};
int row = 0;
int column = 0;
vector<string> wordsFound;
clock_t start;
double duration;
vector<string> words;
vector<vector<int> > locations;
//store words from dictionary into vector
while (getline(dict, word))
{
words.push_back(word);
}
start = clock();
//store grid in a c-array
while (inFile.get(c))
{
if (c != ' ' && c != '\n')
{
grid[row][column] = c;
if (column == 8)
{
column = 0;
row++;
}else
{
column++;
}
}
}
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << grid[i][j] << " ";
}
cout << endl;
}
duration = (clock() - start ) / (double) CLOCKS_PER_SEC;
cout << "Time it took to populate grid (seconds) : " << duration << endl;
start = clock();
//for each character in grid
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
//cout << grid[i][j] << " ";
//for each word
for (int k = 0; k < words.size(); k++)
{
//check if grid letter equals the first letter of word
if (grid[i][j] == words[k][0])
{
//check horizontal vertical and diagonal
for (int l = 1; l <= words[k].size(); l++)
{
if (
//break if no word was found
grid[i-l][j] != words[k][l] &&
grid[i+l][j] != words[k][l] &&
grid[i][j+l] != words[k][l] &&
grid[i][j-l] != words[k][l] &&
grid[i+l][j+l] != words[k][l] &&
grid[i-l][j-l] != words[k][l] &&
grid[i+l][j-l] != words[k][l] &&
grid[i-l][j+l] != words[k][l] )
{
break;
}
else if (l == words[k].size()-1)
{
//else write word found to file
//out << words[k] << " was found at [" <<
//j+1 << "][" << i+1 << "]" << endl;
//add word location to locations
vector<int> location;
location.push_back(j+1);
location.push_back(i+1);
locations.push_back(location);
//add word to wordsFound
wordsFound.push_back(words[k]);
}
}
}
}
}
//cout << endl;
}
duration = (clock() - start ) / (double) CLOCKS_PER_SEC;
cout << "Time it took to finish wordsearch puzzle (seconds) : " << duration << endl;

out << "number of words found: " << wordsFound.size() << endl;

for (int i = 0; i < wordsFound.size(); i++){
out << wordsFound[i] << " was found at [" << locations[i][0] << "][" << locations[i][1] << "]" << endl;
}
out << "number of words not found: " << words.size() - wordsFound.size() << endl;

for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < wordsFound.size(); j++) {
//loop to check if word in dictionary wasn't found and append to output.txt
if (words[i] == wordsFound[j]){
break;
}
else if (j == wordsFound.size()-1){
out << words[i] << " was not found!" << endl;
}
}
}
return 0;
}
1

Другие решения

Посмотрите на следующий код. Надеюсь, понятно, как можно загружать и работать с сеткой. Теперь вам просто нужно загрузить свой словарь и записать результат в файл.

std::vector<char> grid;
unsigned int grid_size = 0;

void load_grid(const std::string &path) {
std::ifstream inFile;
inFile.open(path);

inFile >> grid_size;
for (unsigned int i = 0; i < grid_size*grid_size; i++) {
char letter;
inFile >> letter;
grid.push_back(letter);
}
}

bool search_word(int x, int y, const std::string &word) {
// horizontal
if (x + word.length() <= grid_size) {
unsigned int i = 0;
while (i < word.length() && grid[y*grid_size + x + i] == word[i]) i++;
if (i == word.length()) return true;
}
// vertical
if (y + word.length() <= grid_size) {
unsigned int i = 0;
while (i < word.length() && grid[(y+i)*grid_size + x] == word[i]) i++;
if (i == word.length()) return true;
}
// diagonal
if (x + word.length() <= grid_size && y + word.length() <= grid_size) {
unsigned int i = 0;
while (i < word.length() && grid[(y+i)*grid_size + x + i] == word[i]) i++;
if (i == word.length()) return true;
}
return false;
}

int main() {

load_grid("wordsearch_grid.txt");

for (unsigned int x = 0; x < grid_size; x++) {
for (unsigned int y = 0; y < grid_size; y++) {
if (search_word(x, y, "WORLD")) {
std::cout << "WORLD starts at: " << x << " " << y << std::endl;
}
}
}

return 0;
}
1

По вопросам рекламы [email protected]