diff --git a/2018/08/lib/Entry.pm b/2018/08/lib/Entry.pm new file mode 100644 index 0000000..1022109 --- /dev/null +++ b/2018/08/lib/Entry.pm @@ -0,0 +1,55 @@ +package Entry; + +use Moose; + +use experimental qw/ signatures postderef /; + +use List::AllUtils qw/ sum /; + +has stream => ( + is => 'ro', + required => 1, + traits => [ 'Array' ], + handles => { + splice => 'splice', + }, + trigger => sub($self,$stream) { + my( $nchild, $ndata ) = splice @$stream, 0, 2; + $self->children([ + map { Entry->new( stream => $stream ) } 1..$nchild + ]); + $self->data([ splice @$stream, 0, $ndata ]); + } +); + +has children => ( + is => 'rw', + default => sub { [] }, +); + +has data => ( + is => 'rw', + default => sub { [] }, +); + +sub all_data($self) { + return $self->data->@*, map {$_->all_data} $self->children->@*; +} + +sub value($self) { + if( ! $self->children->@* ) { + return sum $self->data->@* + } + + return sum + map { $_->value } + grep { $_ } + map { $self->children->[ $_ ] } + grep { $_ >= 0 } + map { $_ -1 } + $self->data->@*; + + +} + +1; diff --git a/2018/08/sol1.pl b/2018/08/sol1.pl index ff67a2e..03cc3ca 100644 --- a/2018/08/sol1.pl +++ b/2018/08/sol1.pl @@ -5,14 +5,14 @@ use experimental qw/ postderef /; +use lib './lib'; + +use Entry; + +use List::AllUtils qw/ sum /; + my @input = split / /, <>; -parse_metadata(@input); +my $entry = Entry->new( stream => \@input ); -sub parse_metadata($nbr_children, $nbr_metadata, @payload) { - my @meta; - push @meta, pop @payload for 1..$nbr_metadata; - - - -} +say sum $entry->all_data; diff --git a/2018/08/sol2.pl b/2018/08/sol2.pl new file mode 100644 index 0000000..2ad8d6a --- /dev/null +++ b/2018/08/sol2.pl @@ -0,0 +1,16 @@ +use 5.20.0; +use warnings; +use experimental qw/ + signatures + postderef +/; + +use lib './lib'; + +use Entry; + +my @input = split / /, <>; + +my $entry = Entry->new( stream => \@input ); + +say $entry->value;