aboutsummaryrefslogtreecommitdiff
path: root/challenge-113
diff options
context:
space:
mode:
authorAdam Russell <ac.russell@live.com>2021-05-21 01:04:52 -0400
committerAdam Russell <ac.russell@live.com>2021-05-21 01:04:52 -0400
commit7a0fb1fd9b13bb448af8778993cd790874a19d3d (patch)
tree23257f28f03bd26ee441c05e998c6b9435dc7d3a /challenge-113
parent0190ce836b22b4fae93758cf8e5379770ceb5a2c (diff)
downloadperlweeklychallenge-club-7a0fb1fd9b13bb448af8778993cd790874a19d3d.tar.gz
perlweeklychallenge-club-7a0fb1fd9b13bb448af8778993cd790874a19d3d.tar.bz2
perlweeklychallenge-club-7a0fb1fd9b13bb448af8778993cd790874a19d3d.zip
Perl solution for Task #2
Diffstat (limited to 'challenge-113')
-rw-r--r--challenge-113/adam-russell/perl/ch-2.pl59
1 files changed, 59 insertions, 0 deletions
diff --git a/challenge-113/adam-russell/perl/ch-2.pl b/challenge-113/adam-russell/perl/ch-2.pl
index e69de29bb2..1b9f0bafd8 100644
--- a/challenge-113/adam-russell/perl/ch-2.pl
+++ b/challenge-113/adam-russell/perl/ch-2.pl
@@ -0,0 +1,59 @@
+use strict;
+use warnings;
+##
+# You are given a Binary Tree.
+# Write a script to replace each node of the tree with
+# the sum of all the remaining nodes.
+##
+use Graph;
+use Graph::Easy::Parser;
+
+sub dfs_update{
+ my($graph, $vertex, $graph_updated, $previous) = @_;
+ my @successors = $graph->successors($vertex);
+ for my $successor (@successors){
+ my $sum_remaining = sum_remaining($graph, $vertex);
+ $graph_updated->add_edge($previous, $sum_remaining) if $previous;
+ dfs_update($graph, $successor, $graph_updated, $sum_remaining);
+ }
+ $graph_updated->add_edge($previous, sum_remaining($graph, $vertex)) if !@successors;
+}
+
+sub sum_remaining{
+ my($graph, $visited) = @_;
+ my $sum = 0;
+ for my $vertex ($graph->vertices()){
+ $sum += $vertex if $vertex != $visited;
+ }
+ return $sum;
+}
+
+sub display_graph{
+ my($graph) = @_;
+ my $s = $graph->stringify();
+ my @s = split(/,/, $s);
+ my @lines;
+ for my $n (@s){
+ my @a = split(/-/, $n);
+ push @lines, "[ $a[0] ] => [ $a[1] ]";
+ }
+ my $parser = new Graph::Easy::Parser();
+ my $graph_viz = $parser->from_text(join("", @lines));
+ print $graph_viz->as_ascii();
+}
+
+MAIN:{
+ my $graph = new Graph();
+ my $graph_updated = new Graph();
+ my $root = 1;
+ $graph->add_edge($root, 2);
+ $graph->add_edge($root, 3);
+ $graph->add_edge(2, 4);
+ $graph->add_edge(4, 7);
+ $graph->add_edge(3, 5);
+ $graph->add_edge(3, 6);
+ dfs_update($graph, $root, $graph_updated);
+ display_graph($graph);
+ display_graph($graph_updated);
+}
+