MarkovChainLanguageModel { public String generate(Locale language, int length, String encoding) throws UnsupportedEncodingException{ Matrix chain = this.chains.get(language); if(chain == null) return null; double[][] chainData = chain.getArray(); long[] chainCount = this.chainCounts.get(language); int currentIndex = 0; byte[] newString = new byte[length]; Random r = new Random(); for (int i = 0; i < length; i++) { double prob = r.nextDouble(); double[] currentLine = chainData[currentIndex]; double probSum = 0.0; int newIndex = 0; while(probSum+(currentLine[newIndex]/ chainCount[currentIndex]) < prob){ 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{ MarkovChainLanguageModel model = new MarkovChainLanguageModel(); model.train(Locale.ENGLISH, "This is an english sentence", "UTF-8"); System.out.println(model.generate(Locale.ENGLISH, 100, "UTF-8")); }