-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-12-star-2.pl
executable file
·86 lines (72 loc) · 2.37 KB
/
day-12-star-2.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
#!/usr/bin/perl
use warnings;
use 5.036;
use List::Util qw(sum);
my $sum;
my %cache;
while(<>) {
chomp;
(my $springs, my $groups) = split(/ /);
$springs = join('?', $springs, $springs, $springs, $springs, $springs);
$groups = join(',', $groups, $groups, $groups, $groups, $groups);
my @groups = map { int $_ } split(/,/, $groups);
my $key = "$springs,@groups";
$cache{$key} =
$sum += &countOptions($springs, \@groups);
}
say $sum;
sub countOptions($springs, $groupsRef) {
my @groups = @{$groupsRef};
my $key = "$springs,@groups";
if (exists $cache{$key}) {
return $cache{$key};
}
while (1) {
if ($#groups < 0) {
# say "Springs: $springs, groups: @groups";
my $hasSprings = $springs =~ /\#/;
return $hasSprings ? &save($key, 0) : &save($key, 1);
} elsif ((length $springs) <= 0) {
return &save($key, 0);
} elsif (substr($springs, 0, 1) eq '.') {
$springs =~ s/^\.//;
next;
} elsif (substr($springs, 0, 1) eq '?') {
substr($springs, 0, 1, '.');
# say "Left: $springs";
my $left = &countOptions($springs, \@groups);
substr($springs, 0, 1, '#');
# say "Right: $springs";
my $right = &countOptions($springs, \@groups);
return &save($key, $left + $right);
} elsif (substr($springs, 0, 1) eq '#') {
if ($#groups < 0) {
return &save($key, 0);
} elsif ((length $springs) < $groups[0]) {
return &save($key, 0);
} elsif (substr($springs, 0, $groups[0]) =~ /\./) {
return &save($key, 0);
} elsif ($#groups == 0) {
$springs = substr($springs, $groups[0]);
shift @groups;
next;
} else {
if (length $springs < $groups[0] + 1) {
return &save($key, 0);
} elsif (substr($springs, $groups[0], 1) eq '#') {
return &save($key, 0);
}
$springs = substr($springs, $groups[0]+1);
shift @groups;
next;
}
} else {
say "Wrong input: $springs";
return 0;
}
}
}
sub save($key, $value) {
$cache{$key} = $value;
return $value;
}