From c1cae2ec6d4c6493d08998d5ad7158fc42192547 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Thu, 5 Dec 2024 07:34:45 -0800 Subject: [PATCH] [2024][ruby][5.x] --- 2024/ruby/day_05.rb | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 2024/ruby/day_05.rb diff --git a/2024/ruby/day_05.rb b/2024/ruby/day_05.rb new file mode 100644 index 0000000..d01a96f --- /dev/null +++ b/2024/ruby/day_05.rb @@ -0,0 +1,44 @@ +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__ +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