Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define MAX_WORD_SIZE (50)
- typedef struct {
- char* w1;
- char* w2;
- } anagram_t;
- int anagram(char* word1, char* word2)
- {
- size_t i;
- char* w;
- if (strlen(word1) != strlen(word2))
- return 0;
- if (strcmp(word1, word2) == 0)
- return 0;
- for (i = 0; i < strlen(word1); ++i) {
- w = strchr(word2, word1[i]);
- if (w == NULL)
- return 0;
- *w = '-';
- }
- return 1;
- }
- int cmp(anagram_t* a, char* w1, char* w2)
- {
- if (strcmp(a->w1, w1) == 0 &&
- strcmp(a->w2, w2) == 0)
- return 1;
- if (strcmp(a->w1, w2) == 0 &&
- strcmp(a->w2, w1) == 0)
- return 1;
- return 0;
- }
- int main(int argc, char** argv)
- {
- char** words;
- char buff[MAX_WORD_SIZE];
- size_t p, w, mw, count, ma;
- int t;
- anagram_t** a;
- int c;
- FILE* fp;
- if (argc != 2)
- return 1;
- fp = fopen(argv[1], "r");
- if (fp == NULL) {
- printf("File not found.\n");
- return 1;
- }
- words = malloc(100 * sizeof(char*));
- if (words == NULL)
- return 1;
- w = 0;
- mw = 100;
- p = 0;
- while ((c = fgetc(fp)) != EOF) {
- if (c >= 'A' && c <= 'Z')
- c += 32;
- if (c < 'a' || c > 'z') {
- if (p <= 1) {
- p = 0;
- continue;
- }
- if (w == mw) {
- mw += 100;
- words = realloc(words, mw * sizeof(char*));
- if (words == NULL)
- return 1;
- }
- words[w] = malloc(p + 1);
- if (words[w] == NULL)
- return 1;
- memcpy(words[w], buff, p);
- words[w][p] = '\0';
- w += 1;
- p = 0;
- } else {
- buff[p++] = c;
- }
- }
- fclose(fp);
- count = 0;
- ma = 50;
- a = malloc(ma * sizeof(anagram_t*));
- if (a == NULL)
- return 1;
- for (p = 0; p < w - 1; ++p) {
- for (mw = p + 1; mw < w; ++mw) {
- memcpy(buff, words[mw], strlen(words[mw]) + 1);
- if (anagram(words[p], buff)) {
- for (t = 0; t < count; ++t) {
- if (cmp(a[t], words[p], words[mw])) {
- t = -1;
- break;
- }
- }
- if (t > -1) {
- if (count == ma) {
- ma += 50;
- a = realloc(a, ma *
- sizeof(anagram_t*));
- if (a == NULL)
- return 1;
- }
- a[count] = malloc(sizeof(anagram_t));
- a[count]->w1 = words[p];
- a[count]->w2 = words[mw];
- count += 1;
- }
- }
- }
- }
- printf("Number of anagrams: %lu\n", count);
- for (ma = 0; ma < count; ++ma)
- printf("%s, %s\n", a[ma]->w1, a[ma]->w2);
- free(a[ma]);
- free(a);
- for (ma = 0; ma < w; ++ma)
- free(words[ma]);
- free(words);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement