The weekly challenge 285 - Task 1: No Connection

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-285/#TASK1
 3 #
 4 # Task 1: No Connection
 5 # =====================
 6 #
 7 # You are given a list of routes, @routes.
 8 #
 9 # Write a script to find the destination with no further outgoing connection.
10 #
11 ## Example 1
12 ##
13 ## Input: @routes = (["B","C"], ["D","B"], ["C","A"])
14 ## Output: "A"
15 ##
16 ## "D" -> "B" -> "C" -> "A".
17 ## "B" -> "C" -> "A".
18 ## "C" -> "A".
19 ## "A".
20 #
21 ## Example 2
22 ##
23 ## Input: @routes = (["A","Z"])
24 ## Output: "Z"
25 #
26 ############################################################
27 ##
28 ## discussion
29 ##
30 ############################################################
31 #
32 # Look at all routes. Mark the beginning of the route as element with
33 # outgoing connections, and add the end of the route as an element
34 # without outgoing connections unless it already exists.
35 # In the end, all elements without any outgoing connections can be
36 # printed.
37 
38 use strict;
39 use warnings;
40 
41 no_connection(["B","C"], ["D","B"], ["C","A"]);
42 no_connection(["A","Z"]);
43 
44 sub no_connection {
45    my @routes = @_;
46    print "Input: (" . join(", ", map { "[\"" . $_->[0] . "\", \"" . $_->[1] . "\"]"  } @routes) . ")\n";
47    my $connections = {};
48    foreach my $route (@routes) {
49       $connections->{$route->[0]} = 1;
50       $connections->{$route->[1]} ||= 0;
51    }
52    my @output = ();
53    foreach my $connection (sort keys %$connections) {
54       push @output, $connection unless $connections->{$connection};
55    }
56    print "Output: \"" . join("\", \"", @output) . "\"\n";
57 }