From d246206681d68b014aa23fcae646e327e1c4e6e9 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 12 Dec 2022 21:30:10 -0800 Subject: [PATCH] [2022][ruby][13.x] --- 2022/ruby/day_13.rb | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 2022/ruby/day_13.rb diff --git a/2022/ruby/day_13.rb b/2022/ruby/day_13.rb new file mode 100644 index 0000000..21331c4 --- /dev/null +++ b/2022/ruby/day_13.rb @@ -0,0 +1,35 @@ +def compare(left, right) + case [left, right] + in [left, nil] + 1 + in [Integer, Integer] + left <=> right + in [Array, Array] + left.zip(right).each do |left, right| + case compare(left, right) + when -1 then return -1 + when 0 # no-op + when 1 then return 1 + end + end + (left.size == right.size) ? 0 : -1 + else + compare(Array(left), Array(right)) + end +end + +# part one +# pairs = ARGF.read.split("\n\n") +# pairs = pairs.map {|pair| pair.lines(chomp: true).map { eval(_1) }} + +# p pairs.map.with_index {|(left,right),i| +# [compare(left, right), i+1] +# }.select {|cmp,_| cmp == -1 }.sum(&:last) + +# part two +pairs = ARGF.read.lines(chomp: true).reject(&:empty?).map { eval(_1) } +pairs << [[2]] << [[6]] +pairs = pairs.sort { compare(_1, _2) } +a = pairs.index([[2]]) +b = pairs.index([[6]]) +p (a+1)*(b+1)