Browse Source

Fixed anagram finding with letters pool

master
alistair 4 years ago
parent
commit
b716d3960a
  1. 3
      Makefile
  2. 57
      main.c

3
Makefile

@ -3,6 +3,9 @@ GCC = gcc -O3 --static @@ -3,6 +3,9 @@ GCC = gcc -O3 --static
default: main.c
$(GCC) main.c -o banagram
debug: main.c
gcc -Wall -g -o banagram main.c
install: default
cp banagram /usr/bin/banagram

57
main.c

@ -67,13 +67,18 @@ int get_minimum_match(char *word, int added, char *allowed) { @@ -67,13 +67,18 @@ int get_minimum_match(char *word, int added, char *allowed) {
char line[LINELENGTH];
int err;
int len = strlen(word);
int *min_letter_counts = count_char(word);
if (!min_letter_counts) {
int *orig_word_letter_counts = count_char(word);
if (!orig_word_letter_counts) {
fclose(wfile);
return 1;
}
// loop over every word in the word file and check if it is an allowed
// anagram of word optionally containing some/all of the allowed letters
do {
int *max_letter_counts = NULL;
int *anagram_letter_counts = NULL;
err = fscanf(wfile, "%s\n", line);
if (err == EOF) {
break;
@ -84,47 +89,63 @@ int get_minimum_match(char *word, int added, char *allowed) { @@ -84,47 +89,63 @@ int get_minimum_match(char *word, int added, char *allowed) {
continue;
}
int* word_counts = count_char(line);
if (!word_counts) {
anagram_letter_counts = count_char(line);
if (!anagram_letter_counts) {
continue;
}
if (allowed) {
max_letter_counts = count_char(allowed);
for (int i = 0; i < 26; i++) {
max_letter_counts[i] += orig_word_letter_counts[i];
}
}
bool match = true;
for (int i = 0; i < 26; i++) {
if (min_letter_counts[i] > word_counts[i]) {
for (int i = 0; (i < 26) && match; i++) {
// if word contains a letter that the anagram does not
if (orig_word_letter_counts[i] > anagram_letter_counts[i]) {
match = false;
break;
}
if (allowed && word_counts[i] > 0) {
bool in = false;
for (int j = 0; allowed[j] != '\0'; j++) {
if (allowed[j] == (i + 'a'))
in = true;
}
if (!in) {
// if the anagram contains a letter that is not in the word, or
// pool of available letters
if (allowed) {
if (max_letter_counts[i] < anagram_letter_counts[i]) {
match = false;
break;
}
}
}
}
// print the anagram and the additional letters required
if (match) {
printf("%s +", line);
bool s = false;
printf("%s", line);
for (int i = 0; i < 26; i++) {
int diff = word_counts[i] - min_letter_counts[i];
int diff = anagram_letter_counts[i] - orig_word_letter_counts[i];
if (diff > 0) {
if (!s) {
s = true;
printf(" +");
}
printf(" %d%c", diff, i + 'a');
}
}
printf(" ");
printf("\n");
}
free(anagram_letter_counts);
if (max_letter_counts) {
free(max_letter_counts);
}
} while (err != EOF);
free(min_letter_counts);
free(orig_word_letter_counts);
fclose(wfile);
return 0;
}

Loading…
Cancel
Save