-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordmonger.rb
59 lines (51 loc) · 1.3 KB
/
wordmonger.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require "io/console"
require "json"
require "zlib"
require "set"
def getkey
buf = ""
IO.console.raw{|c| loop{buf += c.read_nonblock(1) rescue break}}
buf
end
KEY_UP = "\e[A"
KEY_DOWN = "\e[B"
KEY_LEFT = "\e[C"
KEY_RIGHT = "\e[D"
class WordPredictor
def initialize(goods = [], bads = [])
@samples_by_letters = Hash.new{|h, k| h[k] = {good: Set.new, bad: Set.new}}
@diphtong_stats = Hash.new(|h, k| h[k] = {good: 0, bad: 0})
goods.each{|w| add_good w}
bads.each{|w| add_bad w}
end
def add_good(sample); add(sample, :good); end
def add_bad(sample); add(sample, :bad); end
def add(sample, status)
samples = samples_by_letters[sample.chars.sort]
if samples[status].add? sample
sample.chars.each_cons(2) do |d|
diphtong_stats[d][status] += 1
end
end
end
def test(sample)
samples_by_letters[sample.chars.sort].each do |status, samples|
return status == :good ? 1.0 : 0.0 if samples.include? sample
end
sample.chars.each_cons(2).map do |a|
stats = diphtong_stats[a]
(stats[:good] + 1) / (stats[:good] + stats[:bad] + 2)
end.reduce(&:*, 1)
end
def serialize
[
@samples_by_letters.values.map{|x| x[:good]}.flatten,
@samples_by_letters.values.map{|x| x[:bad]}.flatten
]
end
def self.deserialize(x); self.new(*x); end
end
class WordGrid
def self.input
end
end