#!/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