Skip to content

Instantly share code, notes, and snippets.

@matutter
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save matutter/a28269f5bce5b7eeff6a to your computer and use it in GitHub Desktop.

Select an option

Save matutter/a28269f5bce5b7eeff6a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
int populate( char word_array[40][15] )
{
FILE *words;
int end;
/* open the file */
words = fopen( "file.txt", "r" );
/* if the file doesn't exists, don't run the program */
if( words == 0 )
{
printf("CANNOT OPEN\n");
exit(1);
}
/* 'i' will track the total amount of words */
int i = 0;
/* real each word, stop at the EOF (end of file) */
for (i = 0; fscanf(words, "%s", word_array[i] ) != EOF ; ++i);
/* close the file, you're done reading it */
fclose( words );
/* the amount of words read */
return i - 1;
}
void showit(int size, char words[40][15])
{
int i;
for (i = 0; i < size; ++i)
{
if( words[i][0] != 0 )
printf("%s\n", words[i]);
}
}
/* **GOAL** Remove every word WITHOUT duplicates */
void detect(int size, char words[40][15])
{
int i, j;
/* 1. check each word */
for ( i=0; i < size; ++i)
{
/* 3. reset this flag on each new word */
int match = 0;
/* 2. against every other word after it */
for ( j=i+1; j < size; ++j)
{
/* 4. if they match, flag them to leave it alone */
if( !strcmp(words[i], words[j]) )
match = 1;
}
/* 5. if it wasn't flagged delete it */
if( !match )
/* 6. remove the word if there's no duplicate */
words[i][0] = 0;
}
}
int main(void)
{
char word_array[40][15];
int size = populate( word_array );
showit( size, word_array );
detect( size, word_array );
printf("___________________\n");
showit( size, word_array );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment