Skip to content

Instantly share code, notes, and snippets.

@wolfiestyle
Created April 23, 2012 01:45
Show Gist options
  • Save wolfiestyle/2468154 to your computer and use it in GitHub Desktop.
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
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