一応パスしたけど75点^ ^;
Trigramのアルゴリズムが怪しいので多分そこが問題。まあ良として先に。
N-gramを使って特定ワードの次ぎに来るワードの確率リストを出力。
#!/usr/bin/env ruby def predict(n, pre_word, text) words = text.scan(/\w+/) n_grams = build_ngrams(words, n) post_words = find_post_words(pre_word, n_grams) predict_by_word(post_words) end def build_ngrams(words, n) # words = [''] * (n-1) + words + [''] * (n-1) words.each_cons(n) end def find_post_words(pre_word, n_grams) n_grams.select { |words| words[0..-2].include? pre_word } .map { |words| pos = words.index(pre_word).next; words[pos] } end def predict_by_word(words) words.inject(Hash.new(0)) { |h, w| h[w] += 1; h } .map { |w, n| [w, n/words.size.to_f] } end def pp(result) hash = Hash.new{ |h,k| h[k]=[] } puts result.inject(hash) { |h, (w, pre)| h[pre] << w; h} .sort_by { |pre,_| -pre } .map { |pre, words| words.sort_by(&:downcase).map { |w| format("%s,%.3f", w, pre) }.join(';') }.join(';') end TEXT = %{Mary had a little lamb its fleece was white as snow; And everywhere that Mary went, the lamb was sure to go. It followed her to school one day, which was against the rule; It made the children laugh and play, to see a lamb at school. And so the teacher turned it out, but still it lingered near, And waited patiently about till Mary did appear. "Why does the lamb love Mary so?" the eager children cry;"Why, Mary loves the lamb, you know" the teacher did reply."} ARGF.lines do |line| n, pre_word = line.scan(/\w+/) pp predict(n.to_i, pre_word, TEXT) end
100円〜で好評発売中!M'ELBORNE BOOKS