From 3643356cf0510fe4339c1a130f74a362450403eb Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Sat, 8 Dec 2018 16:26:34 -0500 Subject: [PATCH] day8 --- 2018/08/lib/Entry.pm | 55 ++++++++++++++++++++++++++++++++++++++++++++ 2018/08/sol1.pl | 16 ++++++------- 2018/08/sol2.pl | 16 +++++++++++++ 3 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 2018/08/lib/Entry.pm create mode 100644 2018/08/sol2.pl 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;