summaryrefslogtreecommitdiffstats
path: root/2019/day6/orbits.pl
blob: 9f4aed574f7fc5f13c1044d29a813cfbeeca5846 (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
use strict;
use warnings;

my $file_name = $ARGV[0];

if (not defined $file_name) {
    die "missing filename\n";
}

open my $fh, "<", $file_name or die "Can't open $file_name, $!\n";

my %orbit;

while (<$fh>) {
    chomp;
    my ($from, $to) = split /\)/;
    push @{ $orbit{$from} }, $to;
}

close $fh;

my @to_value = ('---', 'COM');
my $dist = 0;
my $total = 0;

while ( 1 ) {

    my $cur = pop @to_value;

    print $total and exit unless @to_value;

    if ($cur eq '---') {
        unshift @to_value, '---';
        $dist++;
    } else {
        $total += $dist;
        unshift @to_value, @{ $orbit{$cur} } if exists $orbit{$cur};
    }
}