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