オフラインリアルタイムどう書くE05 どきどきトロッコ

めっちゃ汚いけど解き終わった直後のまま載せます

見どころはabcで表せばいいのにhml(high, middle, low)という独自の概念を入れたところです。 「みんな深さ優先するだろうから俺説明するとこないな〜〜」って思いながら解いたら少数派だったのでめっちゃびっくりしました。 今回のどきどき系はちゃんと問題文中に "死" って書いてあっていいなって思いました

あとgoで書いたらchannelの使い方がよくわかんなくてアレがアレだったのでもうちょっと勉強しようと思いましたまる

def init
  plates = [nil] + (1..9).map { Hash.new }

  plates[1]["h"] = %w(h m)
  plates[1]["m"] = %w(m l)
  plates[1]["l"] = %w(l)

  plates[2]["h"] = %w(h l)
  plates[2]["m"] = %w(m)
  plates[2]["l"] = %w(m l)

  plates[3]["h"] = %w(h l)
  plates[3]["m"] = %w(h m)
  plates[3]["l"] = %w(l)

  plates[4]["h"] = %w(h)
  plates[4]["m"] = %w(h m)
  plates[4]["l"] = %w(m l)

  plates[5]["h"] = %w(h)
  plates[5]["m"] = %w(m l)
  plates[5]["l"] = %w(h l)

  plates[6]["h"] = %w(h m)
  plates[6]["m"] = %w(m)
  plates[6]["l"] = %w(h l)

  plates[7]["h"] = %w(h)
  plates[7]["m"] = %w()
  plates[7]["l"] = %w(l)

  plates[8]["h"] = %w()
  plates[8]["m"] = %w(m)
  plates[8]["l"] = %w(l)

  plates[9]["h"] = %w(h)
  plates[9]["m"] = %w(m)
  plates[9]["l"] = %w()

  plates
end

def solve(input)
  plates = input.split('').map(&:to_i).map { |e| init[e] }
  results = %w(h m l).map { |r| d(plates, 0, r) }
  str = []
  str << "a" if results[0]
  str << "b" if results[1]
  str << "c" if results[2]
  str.empty? ? "-" : str.join("")
end

def d(plates, i, r)
  plate = plates[i]
  return true unless plate
  plate[r].each do |nr|
    return true if d(plates, i + 1, nr)
  end
  false
end

def test(input, expected)
  puts solve(input) == expected ? "ok" : "ng"
end

test("1728398", "bc")
test("789", "-")
test("274", "ac")
test("185", "abc")
test("396", "ab")
test("1278", "abc")
test("7659832", "a")
test("178", "bc")
test("189", "ab")
test("197", "a")
test("278", "ac")
test("289", "bc")
test("297", "a")
test("378", "ac")
test("389", "b")
test("397", "ab")
test("478", "c")
test("489", "bc")
test("497", "ab")
test("578", "bc")
test("589", "b")
test("597", "ac")
test("678", "c")
test("689", "ab")
test("697", "ac")
test("899", "b")
test("7172", "ac")
test("54787", "bc")
test("83713", "bc")
test("149978", "-")
test("159735", "abc")
test("1449467", "abc")
test("9862916", "b")
test("96112873", "ab")
test("311536789", "-")
test("281787212994", "abc")
test("697535114542", "ac")