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