Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- my @input = map { chomp; split // } <>;
- # Read in disk
- my @disk;
- my $id = 0;
- while (@input) {
- my $size = shift @input;
- my $gap = shift @input;
- push( @disk, {id => $id++, size => int $size} );
- push( @disk, {id => -1, size => int $gap } ) if ($gap);
- }
- # Defragment disk
- my $idx = $#disk;
- for (my $file_id = $id - 1; $file_id > 0; $file_id--) {
- $idx-- while ($idx >= 0 and $disk[$idx]{id} != $file_id);
- my $span = 0;
- $span++ while ($span < $idx and ($disk[$span]{id} != -1
- or $disk[$span]{size} < $disk[$idx]{size}));
- next if ($span >= $idx);
- my %copy = $disk[$idx]->%*;
- $disk[$idx]{id} = -1;
- splice( @disk, $span, 1, (\%copy, {size => $disk[$span]{size} - $disk[$idx]{size},
- id => -1}) );
- }
- # Calculate checksum
- my $part2 = 0;
- my $pos = 0;
- foreach my $b (@disk) {
- if ($b->{id} != -1 and $b->{size} > 0) {
- for (my $i = 0; $i < $b->{size}; $i++) {
- $part2 += $b->{id} * ($pos + $i);
- }
- }
- $pos += $b->{size};
- }
- say "Part 2: $part2";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement