Follows a program capable of reading words arranged horizontally, vertically and diagonally in a word search contained in a text file.
Words can be accessed through their coordinates:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef enum {
eHorizontal,
eVertical,
eDiagonal
} orientacao_t;
char obter_letra( int col, int linha, FILE * pf )
{
char buf[1024] = {0};
rewind(pf);
while( 0 <= linha-- )
fgets( buf, sizeof(buf), pf );
return buf[ col ];
}
char * obter_palavra( char * p, int col, int linha, int tam, orientacao_t or, FILE * pf )
{
int i = 0;
for( i = 0; i < tam; i++ )
{
switch( or )
{
case eHorizontal :
p[i] = obter_letra( col + i, linha, pf );
break;
case eVertical:
p[i] = obter_letra( col, linha + i, pf );
break;
case eDiagonal:
p[i] = obter_letra( col + i, linha + i, pf );
break;
default:
break;
}
}
p[tam] = '\0';
return p;
}
int main( int argc, char * argv[] )
{
char palavra[50] = {0};
FILE * pf = NULL;
pf = fopen( argv[1], "r" );
printf( "Palavra 1: %s\n", obter_palavra( palavra, 11, 2, 8, eDiagonal, pf ) );
printf( "Palavra 2: %s\n", obter_palavra( palavra, 7, 18, 10, eHorizontal, pf ) );
printf( "Palavra 3: %s\n", obter_palavra( palavra, 5, 8, 8, eVertical, pf ) );
printf( "Palavra 4: %s\n", obter_palavra( palavra, 10, 6, 8, eDiagonal, pf ) );
printf( "Palavra 5: %s\n", obter_palavra( palavra, 9, 16, 4, eHorizontal, pf ) );
printf( "Palavra 6: %s\n", obter_palavra( palavra, 18, 16, 4, eVertical, pf ) );
fclose(pf);
return 0;
}
Test file containing the words VERTICAL
, HORIZONTAL
, DIAGONAL
, GATO
, CACHORRO
and RATO
:
CAQIXCBXXJMDVRANWPMT
YGOQZMQWVKMMJMSIAQDI
XFXOBRWILQJDJYORKGWC
UARIHCBJSDTLIEBSETOH
QSLOCAWZFUYXBASBJTCC
NLJDHZMWYMLVPVGWPNAZ
BBTOCWHEYVCDNGPOLHXO
SDICESRPTQPARRLNNSHZ
XMSKYVIGVDZLCEBBIAOW
UTZABEBHKJNTEHFNPILH
GINPIRMZTJJVLIOZHRRE
NJFRQTLRHBQOSNQRIWOX
CBJTPIEDNWBJKGDJRTIC
SRTWSCSPWFHEMKYGYOXU
OYSCYAPEDMABBFJBZSZN
RQVSILWPWOGNREWNKHHE
JBXFOFFYGGATOJLUMORV
FNVLDATMISHLTVIZEDAL
DZADHEZHORIZONTALXTC
MXOPRHRNNNBXMZNHUOOG
Exit:
Palavra 1: DIAGONAL
Palavra 2: HORIZONTAL
Palavra 3: VERTICAL
Palavra 4: CACHORRO
Palavra 5: GATO
Palavra 6: RATO
It would not be easier to read the entire file at once and then keep doing searches in memory?
– Victor Stafusa
A sample of this file would help a lot.
– Lacobus
I can’t throw the whole file in memory. @Lacobus I edited there with a very small example, but it’s basically a Zxz array with random characters
– Otavio Rocha
If you cannot read the entire file in memory, it would not be possible to have only the last ~30 lines in memory and search only in this data?
– Guto