1
0
Fork 0
advent-of-code-2024/09/9-1.rb

52 lines
829 B
Ruby
Raw Normal View History

2024-12-09 20:16:32 -05:00
#!/usr/bin/env ruby
problem = 9
input = File.read("#{problem}.input")
#input = DATA.read
.chars
.map(&:to_i)
expanded_disk = []
id = 0
type = :file
input.each do
if type == :free
_1.times { expanded_disk << "." }
type = :file
else
_1.times { expanded_disk << id }
id += 1
type = :free
end
end
defragmented_disk = Array.new(expanded_disk.size)
l, r = 0, expanded_disk.size - 1
while l <= r
if expanded_disk[l] != "."
defragmented_disk[l] = expanded_disk[l]
l += 1
elsif expanded_disk[r] == "."
defragmented_disk[r] = expanded_disk[r]
r -= 1
else
defragmented_disk[l] = expanded_disk[r]
defragmented_disk[r] = "."
l += 1
r -= 1
end
end
checksum = defragmented_disk
.map.with_index { _1.to_i * _2.to_i }
.sum
p checksum
__END__
2333133121414131402