aboutsummaryrefslogtreecommitdiff
path: root/source/backronyms.d
blob: 7b3c9e6fcca1724abda392025d6f4e714ca9a20d (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module backronyms;
import std.stdio;
import std.algorithm;
import std.random;
import std.conv;
import std.range;
import std.typecons;

struct BackronymGenerator
{
	WordList nouns;
	WordList adjectives;

	static BackronymGenerator load()
	{
		return BackronymGenerator(
			WordList.fromFile("SimpleWordlists/Wordlist-Nouns-Common-Audited-Len-3-6.txt"),
			WordList.fromFile("SimpleWordlists/Wordlist-Adjectives-All.txt"),
		);
	}

	string formatBackronymList(string word)
	{
		string ret;
		for (int i = 0; i < word.length; i++)
		{
			ret ~= (
				i + 1 == word.length
					? this.nouns : this.adjectives
			).findRandomWord(word[i]);
			ret ~= '\n';
		}
		return ret;
	}
}

struct WordList
{

	string[][char] words;

	string[] findBackronym(string word)
	{
		string[] ret;

		foreach (c; word)
		{
			ret ~= this.findRandomWord(c);
		}

		return ret;
	}

	string findRandomWord(char start)
	{
		return this.words[start].choice;
	}

	static WordList fromFile(string filePath)
	{
		auto file = File(filePath);
		return fromLines(file.byLine.map!(to!string));
	}

	static WordList fromLines(R)(R lines)
			if (isInputRange!R && is(ElementType!R == string))
	{
		WordList ret;

		foreach (line; lines)
		{
			if (line.length == 0)
				continue;

			ret.words[line[0]] ~= line;
		}

		return ret;
	}

}