-
-
Save lucasbuchala/6a156a38d1b6a085de5a2c60a9df4f6f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use feature qw(say state); | |
use List::Util qw(sum0); | |
sub sliced { my ($arr, @i) = @_; @i = grep 0<=$_ && $_<@$arr, map int, @i; @{$arr}[@i] } | |
sub make_tree { | |
my $list = shift; | |
my ($nchild, $ndata) = splice @$list, 0, 2; | |
my @children = map make_tree($list), 1..$nchild; | |
my @data = splice @$list, 0, $ndata; | |
return [ \@data, @children ]; | |
} | |
sub sum_data { | |
my $node = shift; | |
my ($data, @children) = @$node; | |
return sum0(@$data) | |
+ sum0(map sum_data($_), @children); | |
} | |
sub value_of { | |
my $node = shift; | |
my ($data, @children) = @$node; | |
return @children | |
? sum0(map value_of($_), sliced(\@children, map $_-1, @$data)) | |
: sum0(@$data); | |
} | |
sub main { | |
my @list = map int, split ' ', do { local $/; <> }; | |
my $root = make_tree(\@list); | |
say sum_data($root); # part 1 | |
say value_of($root); # part 2 | |
} | |
main; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment