using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Markov
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: markov <file>");
return;
}
string text = File.ReadAllText(args[0], Encoding.ASCII).Replace('\n', ' ').Replace('\r', ' ');
string[] cuvinte = text.Split(' ');
List<string> l = new List<string>(cuvinte), l2 = new List<string>();
l.RemoveAll(delegate(string s) { return s.Length == 0; });
List<string> lcuvinte = new List<string>(l);
l.Sort();
l2.Add(l[0]);
for (int i = 1; i < l.Count; i++)
if (l[i] != l[i - 1])
l2.Add(l[i]);
Dictionary<string, int> hashCuv = new Dictionary<string, int>();
for (int i = 0; i < l2.Count; i++)
hashCuv.Add(l2[i], i);
Dictionary<KeyValuePair<int, int>, List<int>> hashMarkov = new Dictionary<KeyValuePair<int, int>, List<int>>();
KeyValuePair<int, int> kvp;
for (int i = 2; i < lcuvinte.Count; i++)
{
kvp = new KeyValuePair<int, int>(hashCuv[lcuvinte[i - 2]], hashCuv[lcuvinte[i - 1]]);
if (hashMarkov.ContainsKey(kvp) == false)
hashMarkov[kvp] = new List<int>();
hashMarkov[kvp].Add(hashCuv[lcuvinte[i]]);
}
Random r = new Random();
int a = r.Next(lcuvinte.Count - 2);
int b = a + 1;
Console.Write("{0} {1} ", lcuvinte[a], lcuvinte[b]);
a = hashCuv[lcuvinte[a]];
b = hashCuv[lcuvinte[b]];
kvp = new KeyValuePair<int, int>(a, b);
do
{
if (hashMarkov.ContainsKey(kvp) == false)
{
Console.WriteLine();
break;
}
List<int> list = hashMarkov[kvp];
a = b;
b = list[r.Next(list.Count)];
Console.Write("{0} ", l2[b]);
kvp = new KeyValuePair<int, int>(a, b);
} while (true);
}
}
}