summaryrefslogtreecommitdiffstats
path: root/2020/day9/xmas_encoder.pl
diff options
context:
space:
mode:
authorYigit Sever2021-12-13 10:38:11 +0300
committerYigit Sever2021-12-13 10:38:11 +0300
commit74b27ccca31bb757c737dd7fdc02f513f57561b2 (patch)
treee27db4cd0873c81a53d32277446d926d176304e0 /2020/day9/xmas_encoder.pl
parent3919f90cfbfbba26c8e39f979280649f5e08aea8 (diff)
parentac8125750abed263619da4cc6d653bb5ab76f007 (diff)
downloadaoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.tar.gz
aoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.tar.bz2
aoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.zip
Merge remote-tracking branch 'origin/main'
Diffstat (limited to '2020/day9/xmas_encoder.pl')
-rw-r--r--2020/day9/xmas_encoder.pl70
1 files changed, 70 insertions, 0 deletions
diff --git a/2020/day9/xmas_encoder.pl b/2020/day9/xmas_encoder.pl
new file mode 100644
index 0000000..4fdcb9b
--- /dev/null
+++ b/2020/day9/xmas_encoder.pl
@@ -0,0 +1,70 @@
1use strict;
2use warnings;
3use DDP;
4use Smart::Comments;
5use Tie::File;
6use List::Util qw(min max);
7
8tie my @xmas, 'Tie::File', "input" or die "no input present, $!";
9
10my %preamble;
11# because it's easier this way trust me
12my @also_queue;
13my $goalnum;
14
15foreach my $idx (0 .. $#xmas) {
16 if ($idx < 25) {
17 my $t = int($xmas[$idx]);
18 $preamble{$t} = 1;
19 push @also_queue, $t;
20 } else {
21 my $nextnum = int($xmas[$idx]);
22 my $tester = 0;
23 foreach my $num (keys %preamble) {
24 $tester++;
25 if (exists $preamble{$nextnum - $num}) {
26 my $old = shift @also_queue;
27 delete $preamble{$old};
28 push @also_queue, $nextnum;
29 $preamble{$nextnum} = 1;
30 last;
31 }
32 }
33
34 if (not scalar grep { $_ == $nextnum } @also_queue) {
35 $goalnum = $nextnum;
36 print("XMAS weak num: $goalnum\n");
37 last;
38 }
39 }
40}
41
42# find the contiguous set
43
44my @contiguous;
45my $total = 0;
46
47foreach my $curr (@xmas) {
48 if ($total + $curr < $goalnum) {
49 $total += $curr;
50 push @contiguous, $curr;
51 } elsif ($total + $curr > $goalnum) {
52 while ($total + $curr > $goalnum) {
53 my $evictee = shift @contiguous;
54 if (not defined $evictee) {
55 last;
56 }
57 $total -= $evictee;
58 }
59 push @contiguous, $curr;
60 $total += $curr;
61 }
62
63 if ($total == $goalnum) {
64 print(min(@contiguous) + max(@contiguous));
65 p @contiguous;
66 exit;
67 }
68}
69
70untie @xmas;