Markov Code
People have been asking about the Markov Chain code so I'll post it here. Note, I use the " " key to store the valid beginning sequences. If you want, change the KEY_LENGTH for more/less intelligible output.
package com.sciortino.fun;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class MarkovChainer {
private static final int KEY_LENGTH = 3;
private static final Random RANDOM = new Random();
public static void main(String[] p_args) throws IOException {
if (p_args.length != 1) {
System.out.println("This program takes exactly one argument: "
+ "The location of the input file which has exactly one name per line.");
System.exit(1);
}
BufferedReader l_br = new BufferedReader(new FileReader(p_args[0]));
HashMap<String, ArrayList<String>> l_map = getMap(l_br);
ArrayList<String> l_startArray = l_map.get(" ");
for (int i = 0; i < 100; i++) {
StringBuilder l_buf = new StringBuilder();
String l_wordPart = l_startArray.get(RANDOM.nextInt(l_startArray.size()));
while (l_wordPart != null) {
l_buf.append(l_wordPart);
String l_key = l_buf.substring(l_buf.length() - KEY_LENGTH,
l_buf.length());
ArrayList<String> l_nextList = l_map.get(l_key);
if (l_nextList == null) {
break;
}
l_wordPart = l_nextList.get(RANDOM.nextInt(l_nextList.size()));
}
System.out.println(l_buf);
}
}
private static HashMap<String, ArrayList<String>> getMap(BufferedReader l_br)
throws IOException {
HashMap<String, ArrayList<String>> l_map = new HashMap<String, ArrayList<String>>();
l_map.put(" ", new ArrayList<String>());
String l_line = null;
while ((l_line = l_br.readLine()) != null) {
if (l_line.length() <= KEY_LENGTH) {
continue;
}
String l_start = l_line.substring(0, KEY_LENGTH);
l_map.get(" ").add(l_start);
for (int i = 0; i + KEY_LENGTH < l_line.length(); i++) {
String l_key = l_line.substring(i, i + KEY_LENGTH);
String l_next = l_line.substring(i + KEY_LENGTH, i + KEY_LENGTH + 1);
if (!l_map.containsKey(l_key)) {
l_map.put(l_key, new ArrayList<String>());
}
l_map.get(l_key).add(l_next);
}
}
return l_map;
}
}

