summaryrefslogtreecommitdiffstats
path: root/2020/day1/threesum.pl
diff options
context:
space:
mode:
authorYigit Sever2021-12-12 01:24:32 +0300
committerYigit Sever2021-12-12 01:24:32 +0300
commit4bb6f8d06c0e384f3394012b1d48da58ed28cc5e (patch)
treed6478c85c0488a1059567ccd2882cb10039c2546 /2020/day1/threesum.pl
parentae3853b6e8ab02023ccd74baac6dc177b1ee879a (diff)
downloadaoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.gz
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.bz2
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.zip
2020, tracking
Diffstat (limited to '2020/day1/threesum.pl')
-rw-r--r--2020/day1/threesum.pl44
1 files changed, 44 insertions, 0 deletions
diff --git a/2020/day1/threesum.pl b/2020/day1/threesum.pl
new file mode 100644
index 0000000..8f2083a
--- /dev/null
+++ b/2020/day1/threesum.pl
@@ -0,0 +1,44 @@
1use strict;
2use warnings;
3use DDP;
4# use Smart::Comments;
5
6open my $fh, '<', "input" or die "no input present, $!";
7chomp(my @nums = <$fh>);
8close $fh;
9
10@nums = sort { $a <=> $b } @nums;
11
12# fix one index, solve two sum problem
13my $fixed_idx = 0;
14my $l_idx = 1;
15my $r_idx = $#nums;
16
17my $total = $nums[$fixed_idx] + $nums[$l_idx] + $nums[$r_idx];
18
19while ($total != 2020) {
20
21 if ($total < 2020) {
22 $l_idx++; # total too low, increase
23 } else {
24 $r_idx--; # total too high, decrease
25 }
26
27 # fixed index might not be correct
28 if ($l_idx > $r_idx) {
29 $fixed_idx++;
30 $l_idx = $fixed_idx + 1;
31 $r_idx = $#nums;
32 }
33
34 $total = $nums[$fixed_idx] + $nums[$l_idx] + $nums[$r_idx];
35 ### $total
36
37 ### $fixed_idx
38 ### $l_idx
39 ### $r_idx
40
41 # print("fixed: $nums[$fixed_idx]\nleft: $nums[$l_idx]\nright: $nums[$r_idx]\n");
42}
43
44print $nums[$fixed_idx] * $nums[$l_idx] * $nums[$r_idx];