Help Searching vertically

Hello and thank you in advance! here is my issue:
The code takes in a separate file called "words.txt" with 5 rows of 5 letters in those letters is the scrambled word "dog" both horizontally and vertically.

Y R U V G
R T S D C
I F D O G
E D R G E
P W G H T

as the code is now, it searches for the word dog horizontally and tells you where it found it, but I want it to also find the word "dog" vertically..how can i do this? here is my code

#include <iostream>
#include <fstream>

using namespace std;

int main() {
const int ROWS=5;
const int COLS=5;
string s = "DOG";
int foundpos=-1;

// .size() gives us number of letters in string
cout << s.size() << endl;
char puzzle[25];
ifstream fin;
fin.open("words.txt");

// next line reads file characters directly into array
for (int i=0;i<ROWS*COLS;i++) fin >> puzzle[i];
// we don't need the file anymore after we've read it in
fin.close();

// now we start looking for the search word in the array
for (int i=0;i<ROWS*COLS;i++) {
if (puzzle[i]==s[0]) { // search for first character of word
foundpos=i;
for (int j=1;j<s.size();j++) {
if (puzzle[i+j]!=s[j]) { // check remainder of word
foundpos=-1;
break;
}
}
}
// if word found, no need to keep searching, print message and get out of loop
if (foundpos>0) {
cout << s << " was found at pos " << foundpos << endl;
cout << s << " found on row " << (foundpos-foundpos%COLS)/COLS+1 << endl;
cout << s << " found on column " << foundpos%COLS+1 << endl;
break;
}
}

// if we make it this far and foundpos is still -1 word not found
if (foundpos==-1) cout << s << " not found." << endl;
}
Last edited on
one way is to transpose a copy of the puzzle and reuse what you have.
the other way is to iterate down rows instead of across columns.

what I would do is find the starting letter for the word you are searching for (this will be multiples, possibly)
go to one of them, and then
for(i = 0; i < word.length(); i++)
if puzzle[ (firstletterrow+i)*numcols+firstlettercol] == word[i] //its ok else not here.

Dog going down ... the D is at location 8 in puzzle. which is also row1, col3 (0,1,2,3,4 rows/cols)
row1*5+col3 = 5*1+3 = 8, see?
and the next one is
row2*5+3 is 13, right?

if you did this:
puzzle[26]; puzzle[25] = 0;
you could use string functions on puzzle. strstr would find the horizonatal dogs right off. cheating a little, probably not too welcome by your teacher, but if you were really coding this, you might do that (and you can use that on the transpose too, of course, just need to keep the zero in place, and thats also easy because its 'outside' the 5x5)
Last edited on
Topic archived. No new replies allowed.