-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.c
91 lines (80 loc) · 1.97 KB
/
main.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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
#include "commands.h"
Result results[NUM_COMMANDS];
int main(int argc, char **argv)
{
int a, c, found, r;
char current[MAX_TEXT_LENGTH + MAX_DESC_LENGTH + MAX_KEYWORDS_LENGTH
+ MAX_SYNONYM_LENGTH + 4];
for (a = 1; a < argc; ++a)
convert_lower(argv[a]);
for (c = 0; c < NUM_COMMANDS; ++c) {
current[0] = '\0';
sprintf(current, "%s %s %s", commands[c].text,
commands[c].description, commands[c].keywords);
convert_lower(current);
append_synonyms(current);
/* count words in both argv and current */
found = 0;
for (a = 1; a < argc; ++a)
if (strstr(current, argv[a]) != NULL)
++found;
if (found == 0)
continue;
results[c].found = found;
strcpy(results[c].text, commands[c].text);
strcpy(results[c].description, commands[c].description);
}
/* sort results with most words in common with argv at top */
qsort(results, NUM_COMMANDS, sizeof(*results), compare_results);
/* only print MAX_RESULTS results */
for (r = 0; r < MAX_RESULTS && results[r].found > 0; ++r) {
printf("%s\n", results[r].text);
printf(" %s\n", results[r].description);
}
return 0;
}
void convert_lower(char *string)
{
while (*string != '\0') {
*string = tolower(*string);
++string;
}
}
void append_synonyms(char *string)
{
int s, num_words, w;
char *words[MAX_SYNONYM_LENGTH];
for (s = 0; s < NUM_SYNONYMS; ++s) {
num_words = split_string(synonyms[s], words);
for (w = 0; w < num_words; ++w)
if (strstr(string, words[w]) != NULL) {
strcat(string, synonyms[s]);
break;
}
}
}
int split_string(char *string, char **words)
{
char *word;
int i;
word = strtok(string, " ");
for (i = 0; word != NULL; ++i) {
words[i] = malloc(strlen(word) + 1);
strcpy(words[i], word);
word = strtok(NULL, " ");
}
return i;
}
int compare_results(const void *a, const void *b)
{
Result *r1;
Result *r2;
r1 = (Result *)a;
r2 = (Result *)b;
return r2->found - r1->found;
}