From 7f25d2bde6bd2b344a8e63595a214db85cd03a33 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sat, 9 Dec 2023 10:46:51 -0800 Subject: [PATCH] [2023][ruby][9.x] --- 2023/ruby/day_09.rb | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 2023/ruby/day_09.rb diff --git a/2023/ruby/day_09.rb b/2023/ruby/day_09.rb new file mode 100644 index 0000000..3461a7b --- /dev/null +++ b/2023/ruby/day_09.rb @@ -0,0 +1,26 @@ +histories = ARGF.readlines.map { _1.scan(/-?\d+/).map(&:to_i) } + +# part one +p histories + .map {|history| + diffs = [history] + until diffs.last.all?(&:zero?) + diffs << diffs.last.each_cons(2).map { _2 - _1 } + end + + diffs.sum(&:last) + } + .sum + +# part two +p histories + .map {|history| + diffs = [history] + until diffs.last.all?(&:zero?) + diffs << diffs.last.each_cons(2).map { _2 - _1 } + end + + diffs.map(&:first).reverse.inject { _2 - _1 } + } + .sum +