Skip to content
otac0n edited this page Mar 3, 2012 · 3 revisions

In order to get up and running with the Markov library, you should first add a reference using NuGet.

Then, you can use the MarkovChain class to chain between states of type T.

Generating Words Based on a Dictionary

The most basic (and perhaps most common) scenario for Markov chains is to generate words that resemble words in a dictionary.

// Create a chain with letters as the unit of data, basing each letter on the previous 2 letters
var chain = new MarkovChain<char>(2);

// Add words from the dictionary (optionally weighting them).
chain.Add("fool", 1);
chain.Add("food", 1);
chain.Add("loose", 1);

// Randomly generate words that resemble the words in the dictionary.
var rand = new Random();
for (int i = 0; i < 10; i++)
{
    var word = new string(chain.Chain(rand).ToArray());
    Console.WriteLine(word);
}

The result of the program above is something like this:

lood
lool
fool
foose
lood
food
food
lood
lool
loose

Generating Sentences from a Corpus

A slightly more involved scenario is generating sentences based on a corpus. This can be used for a number of things, from parody, to test data.

var chain = new MarkovChain<string>(1);

chain.Add(new[] { "Once", "upon", "a", "time." }, 1);
chain.Add(new[] { "Once", "there", "was", "a", "pig." }, 1);
chain.Add(new[] { "There", "once", "was", "a", "man", "from", "Nantucket." }, 1);

var rand = new Random();

for (int i = 0; i < 10; i++)
{
    var sentence = string.Join(" ", chain.Chain(rand));
    Console.WriteLine(sentence);
}

Console.ReadKey(true);

The result of this program is something like this:

There once was a pig.
There once was a man from Nantucket.
Once upon a time.
Once there was a time.
Once upon a man from Nantucket.
Once upon a time.
Once upon a time.
Once there was a pig.
Once there was a man from Nantucket.
Once upon a pig.

Simulating Market Scenarios

Wikipedia gives an example of Markov chains being used to simulate the stock market. Here is an implementation of that example:

var chain = new MarkovChain<string>(1);

chain.Add(new[] { "Bull" }, "Bull", 900);
chain.Add(new[] { "Bull" }, "Bear", 075);
chain.Add(new[] { "Bull" }, "Recession", 025);
chain.Add(new[] { "Bear" }, "Bull", 150);
chain.Add(new[] { "Bear" }, "Bear", 800);
chain.Add(new[] { "Bear" }, "Recession", 050);
chain.Add(new[] { "Recession" }, "Bull", 250);
chain.Add(new[] { "Recession" }, "Bear", 250);
chain.Add(new[] { "Recession" }, "Recession", 500);

foreach (var item in chain.Chain(new[] { "Bull" }).Take(1000))
{
    Console.WriteLine(item);
    Thread.Sleep(100);
}