From be4b8082d2c67ec48f08c5a39bcfe7cac3cbae0f Mon Sep 17 00:00:00 2001 From: Benjamin Wuethrich Date: Mon, 9 Dec 2024 11:24:07 -0500 Subject: [PATCH] Add 2024, day 9, first part --- 2024/day09/day09a | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100755 2024/day09/day09a diff --git a/2024/day09/day09a b/2024/day09/day09a new file mode 100755 index 00000000..b2742e49 --- /dev/null +++ b/2024/day09/day09a @@ -0,0 +1,32 @@ +#!/usr/bin/env ruby + +disk_map = File.read(ARGV[0]).strip + +expanded = [] +id = 0 + +disk_map.chars.map(&:to_i).each_with_index do |n, idx| + if idx.even? + expanded << [id] * n + id += 1 + else + expanded << ["."] * n + end +end + +expanded.flatten! + +loop do + empty_idx = expanded.index(".") + block_idx = expanded.rindex { _1 != "." } + break unless empty_idx < block_idx + expanded[empty_idx], expanded[block_idx] = expanded[block_idx], expanded[empty_idx] +end + +checksum = 0 + +expanded.each_with_index do |n, idx| + checksum += n * idx unless n == "." +end + +puts checksum