From pygmalion over at Syndk8 forums:
class Markov
{
string rawText = "";
int G = 2;
int O = 1000;
public bool inputStr(string input)
{
this.rawText += input;
return true;
}
public FrequencyTable createFrequencyTable(Array wordArray)
{
int tableMaxSize = wordArray.Length + 1 - this.G;
FrequencyTable table = new FrequencyTable();
for (int i = 0; i < tableMaxSize; i++)
{
string keyStr = "";
string keyword = "";
for (int j = i; j < i + this.G; j++)
{
keyStr += wordArray.GetValue(j) + " ";
}
if (wordArray.Length > i + this.G)
keyword = " " + wordArray.GetValue(i + this.G);
else
keyword = "";
table.add(keyStr, keyword);
}
return table;
}
public string generate()
{
Array wordArray = Regex.Split( this.rawText, @"\s+");
string output = "";
FrequencyTable table = this.createFrequencyTable(wordArray);
string[] lastWords = new string[this.G];
for (int i = 0; i < this.G; i++)
{
output += wordArray.GetValue(i) + " ";
lastWords.SetValue(wordArray.GetValue(i), i);
}
string debug = "";
for (int i = 0; i < this.O; i++)
{
string keyStr = this.lastWordsString(lastWords);
string nextWord = table.randomWord( keyStr );
output += " " + nextWord;
try
{
lastWords = this.lastWordsStack(lastWords, nextWord);
}
catch (IndexOutOfRangeException e)
{
//do nothing
continue;
}
debug += " " + i;
}
return Regex.Replace(output, @"\s+", " ");
}
public string[] lastWordsStack(string[] lastWords, string newWord)
{
for (int i = 0; i < this.G-1; i++)
{
lastWords.SetValue(lastWords.GetValue(i + 1), i);
}
lastWords.SetValue(newWord, this.G-1);
return lastWords;
}
public string lastWordsString(string[] lastWords)
{
string output = "";
for (int i = 0; i < this.G; i++)
output += lastWords.GetValue(i) + " ";
output = Regex.Replace(output, @"\s+", " ");
return output;
}
class FrequencyTable
{
Hashtable table = new Hashtable();
public bool add(string key, string value)
{
if (this.table[key] == null)
this.table.Add(key, "");
this.table[key] += value + " ";
return true;
}
public string toString()
{
//return this.table.ToString();
return "";
}
public string randomWord(string keyStr)
{
string tmp = "" + this.table[keyStr];
string[] arr = Regex.Split(tmp, @"\s+");
Random r = new Random();
// return random entry from Array
return "" + arr.GetValue(r.Next(arr.Length-1));
}
}
As was noted there, you may want to replace strings with StringBuilders.
SB