I have a code called unscramble
that takes two files, Jumbled.txt
and dictionary.txt
and finds if any words contain the same characters in both the files or not, for instance, here is a sample input for
Jumbled.txt:
Hello
Wassup
Rigga
Boyka
Popeye
dictionary.txt:
olleH
Yello
elloH
lloeH
aggiR
ggiRa
giRag
yokaB
Bakoy
kaBoy
eyePop
poePye
and the expected output of the code above is:
Hello: olleH elloH lloeH
Wassup: NO MATCHES
Rigga: aggiR ggiRa giRag
Boyka: yokaB Bakoy kaBoy
Popeye: eyePop poePye
Here is my code that attempts to solve it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LEN 50
#define MAX_DICT_WORDS 500000
#define MAX_JUMBLES 10000
char dict[MAX_DICT_WORDS][MAX_WORD_LEN + 1];
int dict_size;
char jumbles[MAX_JUMBLES][MAX_WORD_LEN + 1];
int jumbles_size;
int compare_chars(const void *a, const void *b) {
return *(char *)a - *(char *)b;
}
void sort_chars(char *s) {
qsort(s, strlen(s), sizeof(char), compare_chars);
}
int compare_words(const void *a, const void *b) {
return strcmp((char *)a, (char *)b);
}
void load_dict(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
perror("Error opening dictionary file");
exit(1);
}
dict_size = 0;
char word[MAX_WORD_LEN + 1];
while (fgets(word, MAX_WORD_LEN + 1, fp) != NULL) {
int len = strlen(word);
if (len > 0 && word[len - 1] == '\n') {
word[len - 1] = '\0'; // remove newline
}
if (len > 1 && len <= MAX_WORD_LEN) {
strcpy(dict[dict_size++], word);
}
}
fclose(fp);
qsort(dict, dict_size, sizeof(dict[0]), compare_words);
}
void load_jumbles(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
perror("Error opening jumbles file");
exit(1);
}
jumbles_size = 0;
char word[MAX_WORD_LEN + 1];
while (fgets(word, MAX_WORD_LEN + 1, fp) != NULL) {
int len = strlen(word);
if (len > 0 && word[len - 1] == '\n') {
word[len - 1] = '\0'; // remove newline
}
if (len > 1 && len <= MAX_WORD_LEN) {
strcpy(jumbles[jumbles_size++], word);
}
}
fclose(fp);
}
void unscramble() {
char sorted[MAX_WORD_LEN + 1];
for (int i = 0; i < jumbles_size; i++) {
strcpy(sorted, jumbles[i]);
sort_chars(sorted);
printf("%s: ", jumbles[i]);
int count = 0;
for (int j = 0; j < dict_size && count < 10; j++) {
if (strcmp(sorted, dict[j]) == 0) {
printf("%s ", dict[j]);
count++;
}
}
if (count == 0) {
printf("NO MATCHES");
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <dictionary> <jumbles>\n", argv[0]);
return 1;
}
load_dict(argv[1]);
load_jumbles(argv[2]);
unscramble();
return 0;
}
However, when I do ./unscramble dictionary.txt Jumbled.txt
, this is what I get:
xxxxxxxxx@LAPTOPxxxxxxxx:~$ ./unscramble dictionary.txt Jumbled.txt
lloeHH
: NO MATCHES
giRagR
kaBoyB
poePyep
I've been trying to debug this and change up my code but nothing is working, what is the problem here?