forked from ershad/Snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanagramSolver.c
108 lines (95 loc) · 2.29 KB
/
anagramSolver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* anagramSolver.c
*
* Copyright 2011 Ershad K <[email protected]>
* Licensed under GPL Version 3
*
* Usage: anagramSolver <word>
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 50
void permutations(char *string, int k, int m);
void swap(char *x, char *y);
void openFile();
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
int j, flag;
unsigned int locations[26][2];
int main(int argc, char *argv[])
{
char string[MAX];
if (argc != 2) {
printf ("Usage: anagramSolver <word>\n");
return 1;
}
openFile();
/* Creating index of the word list for fast access */
int k = 0;
unsigned int l = 0;
char first, old = '$';
while ((read = getline(&line, &len, fp)) != EOF) {
l++;
first = line[0];
if (first != old) {
if (line[0] < 'a')
continue;
locations[line[0] - 'a'][0] = line[0];
locations[line[0] - 'a'][1] = ftell(fp) - strlen(line);
k++;
}
old = first;
}
permutations(argv[1], 0, strlen(argv[1]));
return 0;
}
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permutations(char *string, int k, int m)
{
int i;
if (k == m) {
fseek(fp, line[string[0] - 'a'], SEEK_SET);
while ((read = getline(&line, &len, fp)) != EOF) {
flag = 0;
for (j = 0; line[j] != '\n'; j++) {
if (line[j] != string[j])
flag = 1;
}
if (flag == 0 && strlen(string) == j)
printf("%s", line);
}
}
else
for (i = k; i < m; i++){
swap(&string[k], &string[i]);
permutations(string, k+1, m);
swap(&string[k], &string[i]);
}
}
void openFile()
{
char *fileList[] = {"wordlist",
"/usr/share/dict/american-english",
"/usr/share/dict/british-english",
"/usr/share/dict/cracklib-small"};
int f;
for (f = 0; f < 4; f++)
{
fp = fopen(fileList[f],"r");
if (fp != NULL)
break;
}
if (fp == NULL) {
printf("\n Error: Cannot open dictionary file");
exit(1);
}
}