Skip to content

Instantly share code, notes, and snippets.

@lucasbuchala
Created December 8, 2018 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasbuchala/6a156a38d1b6a085de5a2c60a9df4f6f to your computer and use it in GitHub Desktop.
Save lucasbuchala/6a156a38d1b6a085de5a2c60a9df4f6f to your computer and use it in GitHub Desktop.
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