Created
April 23, 2012 01:45
-
-
Save wolfiestyle/2468154 to your computer and use it in GitHub Desktop.
generates a random string from stdin text input using a Nth order markov chain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio, std.array, std.string, std.conv, std.random; | |
enum { ORDER = 2, MAX_RESULT_WORDS = 20 } | |
void main() | |
{ | |
uint[string][string] dict; | |
string[] prev; | |
foreach (line; stdin.byLine()) | |
foreach (word; split(to!string(toLower(line)))) | |
{ | |
if (prev.length == ORDER) | |
++dict[join(prev, " ")][word]; | |
prev ~= word; | |
if (prev.length > ORDER) | |
prev.popFront(); | |
} | |
auto state = dict.keys[uniform(0, dict.length)]; | |
auto result = split(state); | |
for (int i = MAX_RESULT_WORDS; i && state in dict; --i) | |
{ | |
auto word = dict[state].keys[dice(dict[state].values)]; | |
result ~= word; | |
state = join(result[$-ORDER .. $], " "); | |
} | |
writeln(join(result, " ")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment