From 4a6ddab6da2bfce1c97a1138ba529f9b9691d998 Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Mon, 12 May 2025 20:33:57 +0200 Subject: Initial commit --- source/backronyms.d | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 source/backronyms.d (limited to 'source/backronyms.d') diff --git a/source/backronyms.d b/source/backronyms.d new file mode 100644 index 0000000..7b3c9e6 --- /dev/null +++ b/source/backronyms.d @@ -0,0 +1,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; + } + +} -- cgit