aboutsummaryrefslogtreecommitdiff
path: root/challenge-093/perlboy1967/perl/ch-2.pl
blob: c7ddb43fb03a589fb4d5351b248037cd5541e478 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/perl

# Perl Weekly Challenge - 093
# - https://perlweeklychallenge.org/blog/perl-weekly-challenge-093/
#
# Task 2 - Sum Path
#
# Author: Niels 'PerlBoy' van Dijke

use v5.16;
use strict;
use warnings;

use List::Util qw(sum);
use Data::Printer;

sub treeTotal(\@\@\%);

# Unbuffered STDOUT
$|++;

my %tree = ( 
  'Tree 1' => {
    1 => { 
      2 => { 
        3 => undef,
        4 => undef,
      }
    }
  },
  'Tree 2' => {
    1 => { 
      2 => { 
        4 => undef
      },
      3 => {
        5 => undef,
        6 => undef,
      }
    }
  },
  'Tree 3' => {
    3 => {
      9 => undef,
      3 => {
        2 => undef,
        1 => undef,
      },
    }
  },
);

foreach my $case (sort keys %tree) {
  my (@sum, @nodes);

  treeTotal(@sum, @nodes, %{$tree{$case}});

  my $sum = sum(map{sum @$_} @sum);

  printf "===============================\n";
  printf "Tree: '%s'\n", $case;
  printf "Sum: %d\n", $sum;
  printf "Paths: (%s)\n", join('),(', map {join(',', @$_)} @sum);
  printf "===============================\n\n";
}

sub treeTotal (\@\@\%) {
  my ($arT, $arN, $hr) = @_;
  my @n = @$arN;

  foreach my $k (keys %$hr) {
    if (scalar(keys %{$hr->{$k}})) {
      push(@n, $k);
      treeTotal(@$arT, @n, %{$hr->{$k}});
      pop(@n);
    } else {
      push(@$arT, [@n, $k]);
    }
  }
}