Last active
September 1, 2015 11:37
-
-
Save AyaMorisawa/f980c16e5050c621878f to your computer and use it in GitHub Desktop.
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
function markov<T>(findFirst: () => T[][], findNext: (previous: T) => T[][]): T[][] { | |
function chooseRandom<T>(xs: T[]): T { | |
return xs[Math.floor(Math.random() * xs.length)]; | |
} | |
function last<T>(xs: T[]): T { | |
return xs[xs.length - 1]; | |
} | |
var result: T[][] = []; | |
result.push(chooseRandom(findFirst())); | |
while (true) { | |
var previous = last(last(result)); | |
if (previous === null) { | |
break; | |
} | |
var next = findNext(previous); | |
if(next.length === 0) { | |
break; | |
} | |
result.push(chooseRandom(next).slice(1)); | |
} | |
return result; | |
} | |
(function() { | |
var data: string[][] = [ | |
[null, "私", "は"], | |
["私", "は", "りんご"], | |
["は", "りんご", "が"], | |
["りんご", "が", "好き"], | |
["が", "好き", "だ"], | |
["好き", "だ", null], | |
[null, "彼", "は"], | |
["彼", "は", "みかん"], | |
["は", "みかん", "が"], | |
["みかん", "が", "好き"], | |
["が", "好き", "だ"], | |
["好き", "だ", null] | |
]; | |
var result = markov<string>( | |
() => data.filter(xs => xs[0] === null), | |
previous => data.filter(xs => xs[0] === previous)); | |
document.write(result.map(xs => xs.join('')).join('')); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment