Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created April 4, 2011 02:52
Show Gist options
  • Save radiofreejohn/901079 to your computer and use it in GitHub Desktop.
Save radiofreejohn/901079 to your computer and use it in GitHub Desktop.
open a dictionary file and return a random word
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
/*
I wrote this as a sort of challenge, I wanted to pass random words into the K&R exercise
that generates a hash table of key value pairs to see how quickly the hashes stack up on
one another. I could have easily piped random words to the input, but that's not painful
at all...
*/
char **opendict(int *,int);
char *randomword();
int main(void)
{
// randomword can take a size argument which will limit the random word to contain
// at least size characters.
printf("%s\n", randomword());
return 0;
}
char *randomword(int size)
{
// seems like it would make more sense to return count and pass a pointer to the dict
// but I'm not sure if that is allowed since I haven't pre-allocated space for dict
int count;
char **dict;
dict = opendict(&count,size);
srand(clock());
return dict[rand() % (count-1)];
}
char **opendict(int *count, int size)
{
// maybe it is more graceful to read the full file in, then let
// randomword handle filtering the list to the right size and
// returning the element.
// That would likely take longer though, since it would have to
// filter every time it was called (unless it keeps a second
// copy with the size X, only changing if X changes.
//
// The present solution uses less memory.
FILE *fp;
static int i;
static int wordSize;
static int fileRead;
static char **words;
// This fixes a bug, if randomword was called with a parameter, say 10
// then future runs, even if randomword was changed to have a parameter of 3
// would only contain a list of words of length >= 10.
// Now if size is changed, the file is re-read.
if (wordSize != size)
{
fileRead = 0;
}
// hopefully, any call to opendict will return the words pointer
// without re-opening the dict file again and again
if (fileRead == 0)
{
i = 0;
char word[50];
words = malloc(sizeof(char *));
fp = fopen("/usr/share/dict/web2", "r");
while (fscanf(fp,"%s", word) == 1)
{
if (strlen(word) >= size)
{
words[i] = strdup(word);
i++;
words = realloc(words, sizeof(char *)*(i+1));
}
}
fclose(fp);
wordSize = size;
}
*count = fileRead = i;
return words;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment