Skip to content

Instantly share code, notes, and snippets.

@lnicola
Created June 20, 2014 16:04
Show Gist options
  • Save lnicola/f92124b1844abf5fed1e to your computer and use it in GitHub Desktop.
Save lnicola/f92124b1844abf5fed1e to your computer and use it in GitHub Desktop.
simple text generator based on Markov chains
using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static void Main(string[] args)
{
var input = "foo bar baz foo bar qux".Split();
var table = input.Zip(input.Skip(1), Tuple.Create)
.Zip(input.Skip(2), Tuple.Create)
.ToLookup(p => p.Item1, p => p.Item2);
Func<Tuple<string, string>, Random, IEnumerable<string>> generate = null;
generate = (key, random) => new[] { key.Item1 }.Concat(key.Item2 == null ? new string[] { } : new[] { 0 }.SelectMany(_ => generate(Tuple.Create(key.Item2, table[key].ElementAtOrDefault(random.Next(table[key].Count()))), random)));
Console.WriteLine(String.Join(" ", generate(table.First().Key, new Random()).Take(50)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment