Created
July 18, 2014 13:49
-
-
Save jooyunghan/a0b335cf30e61874aa45 to your computer and use it in GitHub Desktop.
Random text generation example (The Practice of Programming)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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