-
Notifications
You must be signed in to change notification settings - Fork 0
/
day09.pl
111 lines (87 loc) · 2.16 KB
/
day09.pl
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/perl -l
use warnings;
use strict;
use List::Util qw(reduce);
sub getNum {
my $arr = $_[0];
return int(substr( $arr->[$_[1]], $_[2], 1 ));
}
sub isInBasin {
my $basin = $_[0];
my $row = $_[1];
my $col = $_[2];
for (my $i = 0; $i < scalar @{ $basin }; $i += 2) {
if ( $row == $basin->[$i] && $col == $basin->[$i + 1]) {
return 1;
}
}
return 0;
}
sub grow {
my $arr = $_[0];
my $basin = $_[1];
my $row = $_[2];
my $col = $_[3];
if (getNum($arr, $row, $col) == 9) {
return;
}
if (isInBasin($basin, $row, $col)) {
return;
}
push(@$basin, $row);
push(@$basin, $col);
if ($row > 0 ) {
grow($arr, $basin, $row - 1, $col);
}
if ($row < scalar @{ $basin } - 1) {
grow($arr, $basin, $row + 1, $col);
}
if ($col > 0 ) {
grow($arr, $basin, $row, $col - 1);
}
if ($col < length($arr->[0]) - 1 ) {
grow($arr, $basin, $row, $col + 1);
}
}
sub getRisk {
my $arr = $_[0];
my $row = $_[1];
my $col = $_[2];
my $basins = $_[3];
my $l = length($arr->[0]) - 1;
my $num = getNum($arr, $row, $col);
if ( ( $col > 0 ? $num < getNum($arr, $row, $col - 1) : 1 ) &&
( $col < length($arr->[0]) - 1 ? $num < getNum($arr, $row, $col + 1) : 1 ) &&
( $row > 0 ? $num < getNum($arr, $row - 1, $col) : 1 ) &&
( $row < scalar @{ $arr } - 1 ? $num < getNum($arr, $row + 1, $col) : 1 ) )
{
my @basin = ();
grow($arr, \@basin, $row, $col);
push(@$basins, ($#basin + 1) / 2);
return $num + 1;
}
return 0;
}
open(FH, '<', 'input.txt') or die $!;
my @arr = ();
while(<FH>){
chomp($_);
push(@arr, $_);
}
# array with size of basins
my @basins = ();
my $risk = 0;
for my $row (0..$#arr) {
for my $col (0..length($arr[0]) - 1) {
$risk += getRisk(\@arr, $row, $col, \@basins);
}
}
## shameless steal
my %seen;
my @top3 = (sort { $b <=> $a }
grep {!$seen{$_}++}
@basins)[0..2];
my $p2 = reduce { $a * $b } @top3;
print("Day 9, part1: $risk");
print("Day 9, part2: $p2");
close(FH);