75 lines
1.2 KiB
Ruby
Executable file
75 lines
1.2 KiB
Ruby
Executable file
#!/usr/bin/env ruby
|
|
|
|
require "debug"
|
|
|
|
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 = expanded_disk.dup
|
|
|
|
start = Time.now
|
|
r = expanded_disk.size - 1
|
|
while r > 0
|
|
if expanded_disk[r] == "."
|
|
r -= 1
|
|
else
|
|
rr = r
|
|
rr -= 1 while expanded_disk[rr] == expanded_disk[r]
|
|
space = r - rr
|
|
|
|
l = expanded_disk.index(".")
|
|
while l < expanded_disk.size
|
|
if expanded_disk[l] != "."
|
|
l += 1
|
|
next
|
|
end
|
|
|
|
ll = l
|
|
ll += 1 while defragmented_disk[ll] == "."
|
|
free = ll - l
|
|
|
|
if l > r
|
|
break
|
|
elsif free >= space
|
|
(l..(l + space - 1)).each { defragmented_disk[_1] = expanded_disk[r] }
|
|
((rr + 1)..r).each { defragmented_disk[_1] = "." }
|
|
break
|
|
else
|
|
l = ll + 1
|
|
end
|
|
end
|
|
|
|
r = rr
|
|
end
|
|
end
|
|
finish = Time.now
|
|
puts "Finished in #{finish - start}"
|
|
|
|
checksum = defragmented_disk
|
|
.map.with_index { _1.to_i * _2.to_i }
|
|
.sum
|
|
|
|
p checksum
|
|
|
|
|
|
__END__
|
|
2333133121414131402
|