MarkovChainLanguageModel { public String generate(Locale language, int length, String encoding) throws UnsupportedEncodingException { final Matrix chain = this.chains.get(language); if (chain == null) return null; final double[][] chainData = chain.getArray(); final long[] chainCount = this.chainCounts.get(language); int currentIndex = 0; final byte[] newString = new byte[length]; final Random r = new Random(); for (int i = 0; i < length; i++) { final double prob = r.nextDouble(); final double[] currentLine = chainData[currentIndex]; double probSum = 0.0; int newIndex = 0; while (probSum + (currentLine[newIndex] / chainCount[currentIndex]) < prob) { final double probForIndex = (currentLine[newIndex++] / chainCount[currentIndex]); probSum += probForIndex; } newString[i] = (byte) (newIndex - 1); currentIndex = newIndex; } return new String(newString, encoding); } MarkovChainLanguageModel(); void train(Locale language, String example, String encoding); void train(Locale language, InputStream stream); String generate(Locale language, int length, String encoding);  }
@Test public void testGenerate() throws UnsupportedEncodingException { final MarkovChainLanguageModel model = new MarkovChainLanguageModel(); model.train(Locale.ENGLISH, "This is an english sentence", "UTF-8"); }