Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created July 18, 2014 13:49
Show Gist options
  • Save jooyunghan/a0b335cf30e61874aa45 to your computer and use it in GitHub Desktop.
Save jooyunghan/a0b335cf30e61874aa45 to your computer and use it in GitHub Desktop.
Random text generation example (The Practice of Programming)
import java.util.*;
public class Markov {
final static int MAX = 100;
public static void main(String[] args) {
Map<List<String>,List<String>> map = new HashMap<>();
List<String> prefix = Arrays.asList("", "");
try (Scanner scanner = new Scanner(System.in)) {
while (scanner.hasNext()) {
String word = scanner.next();
map.putIfAbsent(prefix, new ArrayList<>());
map.get(prefix).add(word);
prefix = Arrays.asList(prefix.get(1), word);
}
map.putIfAbsent(prefix, new ArrayList<>());
map.get(prefix).add("");
}
Random rand = new Random();
prefix = Arrays.asList("", "");
for (int i=0; i<MAX; i++) {
List<String> suffices = map.get(prefix);
String word = suffices.get(rand.nextInt(suffices.size()));
if (word.equals("")) break;
System.out.println(word);
prefix = Arrays.asList(prefix.get(1), word);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment