Day 10: Syntax Scoring

array = [];
File.foreach("import.dat").with_index do |line, line_num|
  array.push(line.strip)
end

t = array[0]
i1=0 # ) 3

i2=0 # ] 57

i3=0 # } 1197

i4=0 # > 25137

result = []
array.each do |line|
  cont = []
  flag = true
  line.each_char do |c|
    if c == "(" || c == "[" || c == "{" || c == "<" then
      cont.push(c)
    elsif c == ")"
      temp = cont.pop
      if temp == "(" then
      else
        i1 = i1+1
        # puts "not matched! Expected rev:#{temp}, found #{c}"

        flag = false
        break
      end
    elsif c == ">"
      temp = cont.pop
      if temp == "<" then
      else
        i4 = i4+1
        # puts "not matched! Expected rev:#{temp}, found #{c}"

        flag = false
        break
      end
    elsif c == "]"
      temp = cont.pop
      if temp == "[" then
      else
        i2 = i2+1
        # puts "not matched! Expected rev:#{temp}, found #{c}"

        flag = false
        break
      end
    elsif c == "}"
      temp = cont.pop
      if temp == "{" then
      else
        i3 = i3+1
        # puts "not matched! Expected rev:#{temp}, found #{c}"

        flag = false
        break
      end
    else
    end
  end
  if flag then
    p cont.reverse
    result.push(cont.reverse)
  end
end

# (: 1 point.

# [: 2 points.

# {: 3 points.

# <: 4 points.


def calc(line)
  score = 0
  line.each do |c|
    if c == "(" then
      score = (score*5) + 1
    end
    if c == "[" then
      score = (score*5) + 2
    end
    if c == "{" then
      score = (score*5) + 3
    end
    if c == "<" then
      score = (score*5) + 4
    end
  end
  return score
end

r = []
result.each do |line|
  r.push(calc(line))
end

r.sort!

p r.size
p r[(r.size)/2]

メモ

Syntax Checkの問題。大学でアルゴリズムを勉強していた時、『queue』の項目で同じような例が出ていたことを思い出す。Queueの特徴を少しおさらいしてからコードを書いたら、割とすんなりいけた。