1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
rules, updates = DATA.read.split("\n\n")

rules = rules.scan(/(\d+)\|(\d+)/).map { _1.map(&:to_i) }
updates = updates.lines.map { _1.split(?,).map(&:to_i) }

correct, incorrect = updates.partition {|pages|
  pages.each_cons(2).all? { rules.include?(_1) }
}

pp correct.sum { _1[_1.length/2] }

pp incorrect.map {|pages|
  pages.sort {|a,b| rules.include?([a,b]) ? -1 : 1 }
}.sum { _1[_1.length/2] }

__END__