From 1429b8312c09b044f468c360095d6cee72ba8595 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 10 Dec 2024 09:16:43 -0800 Subject: [PATCH] [2024][ruby][9.1] --- 2024/ruby/day_09.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 2024/ruby/day_09.rb diff --git a/2024/ruby/day_09.rb b/2024/ruby/day_09.rb new file mode 100644 index 0000000..a1053ad --- /dev/null +++ b/2024/ruby/day_09.rb @@ -0,0 +1,21 @@ +disk_map = DATA.read.chars.each_slice(2) + .flat_map.with_index {|(a,b),i| + [ Array.new(a.to_i, i), Array.new(b.to_i, nil) ] + }.reject(&:empty?) + +while (prev, free = disk_map.each_cons(2).find { _2.include?(nil) }) + tail = disk_map.last + until free.empty? || tail.empty? + prev << tail.shift + free.pop + end + + while disk_map.last.all?(&:nil?) + disk_map.pop + end +end + +pp disk_map.flatten.each.with_index.sum { _1 * _2 } + +__END__ +2333133121414131402