#!/usr/bin/env ruby problem = 5 input = File.readlines("#{problem}.input").map(&:strip) #input = DATA.read.split("\n") split = input.index("") rules = input[0...split].map { _1.split("|").map(&:to_i) } page_sets = input[split+1..].map { _1.split(",").map(&:to_i) } result = page_sets.select do |page_set| rules .select { |a| (page_set & a).sort == a.sort } .all? { |(a, b)| page_set.index(a) < page_set.index(b) } end.map { _1[_1.size / 2] }.sum p result __END__ 47|53 97|13 97|61 97|47 75|29 61|13 75|53 29|13 97|29 53|29 61|53 97|53 61|29 47|13 75|47 97|75 47|61 75|61 47|29 75|13 53|13 75,47,61,53,29 97,61,53,29,13 75,29,13 75,97,47,61,53 61,13,29 97,13,75,29,47