Created
February 7, 2015 06:00
-
-
Save torazuka/8beb5316a360ca07e61c to your computer and use it in GitHub Desktop.
オフラインリアルタイムどう書く#27 分岐と行き止まり Ruby解答
This file contains 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
#!/usr/bin/ruby | |
# http://nabetani.sakura.ne.jp/hena/ord27raswi/ | |
def init() | |
rale = Struct.new(:name, :inp, :out) | |
rales = [] | |
rales << rale.new("a", ["1"], ["b"]) | |
rales << rale.new("b", ["a", "3"], ["c", "5"]) | |
rales << rale.new("c", ["b", "d", "g"], ["4", "6"]) | |
rales << rale.new("d", ["2"], ["c", "e"]) | |
rales << rale.new("e", ["d", "g"], ["5"]) | |
rales << rale.new("f", ["3"], ["g"]) | |
rales << rale.new("g", ["1", "f"], ["h", "e", "c"]) | |
rales << rale.new("h", ["2", "g"], ["4", "i"]) | |
rales << rale.new("i", ["h"], ["6"]) | |
end | |
def parse(input) | |
input.split("") | |
end | |
def deep(start, t_rales, rales, stopped) | |
result = [] | |
tmp = [] | |
t_rales.each{|t| | |
if ["4", "5", "6"].index(t).nil? == false # 終端に該当するか | |
result << start + t | |
elsif stopped.index(t).nil? # 封鎖対象でないか | |
tmp << t | |
end | |
} | |
tmp.each{|t| | |
rales.each{|r| | |
# 着目しているレールが、tmpの要素と一致するか | |
if r.name == t | |
result.concat(deep(start, r.out, rales, stopped)) | |
end | |
} | |
} | |
return result | |
end | |
def solve(start, rales, stopped) | |
result = [] | |
rales.each{|r| | |
# 着目しているレールが封鎖ポイントでないか、送信元にstartを含むか | |
if stopped.index(r.name).nil? && r.inp.index(start).nil? == false | |
result.concat(deep(start, r.out, rales, stopped)) | |
end | |
} | |
return result.uniq | |
end | |
DATA.each{|line| | |
num, input, expected = line.split( /\s+/ ) | |
rales = init() | |
stopped = parse(input) | |
result = [] | |
(1..3).each{ |n| | |
result.concat(solve(n.to_s, rales, stopped)) | |
} | |
result.sort! | |
actual = result.uniq.join(",") | |
error = (actual == expected) ? "" : " ** expected is : #{expected} **" | |
puts "%s -> %s %s" % [input, actual, error] | |
} | |
__END__ | |
#0 befi 14,16,24,26 | |
#1 abc 14,15,16,24,25,26,34,35,36 | |
#2 de 14,15,16,24,26,34,35,36 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment