Java implementation of Trigrams Kata.

Main.java

import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

    public static void main(String[] args) {
        String text = "I wish I may I wish I might";

        String[] words = text.split(" ");

        MultiValuedMap<String, String> trigrams = new ArrayListValuedHashMap<>();

        for (int i = 0; i < words.length - 2; ++i) {
            trigrams.put(words[i] + " " + words[i + 1], words[i + 2]);
        }

        String newText = "I may";
        String key = newText;

        Random random = new Random();

        while (trigrams.containsKey(key)){
            List<String> list = new ArrayList<>(trigrams.get(key));

            String nextText = list.get(random.nextInt(list.size()));
            newText += " " + nextText;

            String[] keyList = key.split(" ");
            key = keyList[1] + " " + nextText;
        }

        System.out.println(newText);
    }
}

 



Java Trigrams
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close