summaryrefslogtreecommitdiff
path: root/modules/abbrgen/abbreviation_gen.cpp
blob: 708bfdf1f67e7818c4d870e9d6946b3ff92e2c4d (plain)
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
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <sys/time.h>

using namespace std;

int main(int argc, char **argv) {
	if (argc != 2 && argc != 3) {
		cout << "Usage: " << argv[0] << " <abbreviation> [number of answers]" << endl;
		return 1;
	}

	char *abbr = argv[1];
	int abbrlen = strlen(abbr);
	transform(abbr, abbr+abbrlen, abbr, ::tolower);
	for (int i = 0; i < abbrlen; i++) {
		if (abbr[i] < 'a' || abbr[i] > 'z') {
			cout << "Abbreviation cannot contain '" << abbr[i] << "'!" << endl;
			return 1;
		}
	}

	struct timeval tv;
	gettimeofday(&tv, NULL);
	srand(1000000 * tv.tv_sec + tv.tv_usec);
	int numanswers = 1;
	if (argc == 3) {
		numanswers = strtol(argv[2], nullptr, 10);
		if (numanswers <= 0) return 0;
	}

	vector<string> dict[26];
	ifstream dictfile("/usr/share/dict/words");
	string line;

	while (getline(dictfile, line)) {
		transform(line.begin(), line.end(), line.begin(), ::tolower);
		if (line[0] >= 'a' && line[0] <= 'z' && all_of(line.begin(), line.end(), ::islower))
			dict[line[0] - 'a'].push_back(line);
	}

	while (numanswers --> 0) {
		for (int i = 0; i < abbrlen; i++) {
			if (i > 0) cout << ' ';
			size_t index = rand() % dict[abbr[i] - 'a'].size();
			cout << dict[abbr[i] - 'a'][index];
		}
		cout << '\n';
	}
	cout.flush();

	return 0;
}