Problem 191

[quote]A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize.

During an n-day period a trinary string is formed for each child consisting of L’s (late), O’s (on time), and A’s (absent).

Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize:

OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA
OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO
AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL
AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA
LAOO LAOA LAAO

How many “prize” strings exist over a 30-day period?[/quote]

[code=ruby]class Solver
def initialize
@sits = []
@ress = []
end
def foo(o, a, l, left)
#memory
res = get_sit(o, a, l, left)
return res if res

return 0 if a == 3
return 0 if l == 2
return 1 if left == 0
reso = foo(0,0, l, left -1)       #O
add_sit(0,0, l, left -1, reso)      
resa = foo(0, a + 1, l, left -1)  #A
add_sit(0, a+1, l, left -1, resa)      
resl = foo(0,0, l+1, left -1)     #L
add_sit(0, 0, l+1, left -1, resl)     
return reso + resa + resl

end

private
def add_sit(o,a,l,left, res)
@sits << [o,a,l,left]
@ress << res
end

def get_sit(o,a,l,left)
index = @sits.index([o,a,l,left])
return @ress[index] if !index.nil?
return false
end
end
s = Solver.new
puts s.foo(0,0,0,30)[/code]