Skip to content

Instantly share code, notes, and snippets.

@mtbarta
Created December 25, 2013 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtbarta/8127895 to your computer and use it in GitHub Desktop.
Save mtbarta/8127895 to your computer and use it in GitHub Desktop.
Single order Markov Chain
using System;
using System.Linq;
using System.Collections.Generic;
namespace Markov4
{
public class Chain<T>
{
private static readonly IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
private readonly Random random = new Random();
private T start = default(T);
private T stop = default(T);
//private int order;
private List<Node<T>> nodes;
public Chain ()
{
//this.order = ord;
this.nodes = new List<Node<T>>();
}
public T Start{
get{ return start;}
private set{}
}
public T Stop{
get{return stop;}
private set{}
}
public IEnumerable<T> GenerateSequence()
{
var curNode = GetNode(default(T));
int count = 0;
while (true)
{
if (curNode.Links.Count == 0)
break;
curNode = curNode.Links[random.Next(curNode.Links.Count)];
if (curNode.Value == null)
break;
yield return curNode.Value;
}
}
public void Train(T fromValue, T toValue)
{
var fromNode = GetNode(fromValue);
var toNode = GetNode(toValue);
fromNode.AddLink(toNode);
}
private Node<T> GetNode(T value)
{
var node = this.nodes.SingleOrDefault(n => comparer.Equals(n.Value, value));
if (node == null)
{
node = new Node<T>(value);
this.nodes.Add(node);
}
return node;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
namespace Markov4
{
public class Node<T>
{
T value;
List<Node<T>> links;
List<int> linkCount;
public Node (T val)
{
value = val;
links = new List<Node<T>>();
linkCount = new List<int>();
}
public T Value
{
get{return this.value;}
set{this.value = value;}
}
public List<Node<T>> Links
{
get { return this.links;}
}
public int GetLinkCountIndex(Node<T> input)
{
return this.links.IndexOf (input);
}
public void AddLink (Node<T> ToNode)
{
if(this.links.Contains (ToNode))
{
//if node exists already, increment count.
int index = GetLinkCountIndex(ToNode);
this.linkCount[index]++;
return;
}
else
{
this.links.Add (ToNode);
this.linkCount.Add(1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment