diff options
| author | Yigit Sever | 2021-12-13 10:38:11 +0300 |
|---|---|---|
| committer | Yigit Sever | 2021-12-13 10:38:11 +0300 |
| commit | 74b27ccca31bb757c737dd7fdc02f513f57561b2 (patch) | |
| tree | e27db4cd0873c81a53d32277446d926d176304e0 /2020/day1/threesum.pl | |
| parent | 3919f90cfbfbba26c8e39f979280649f5e08aea8 (diff) | |
| parent | ac8125750abed263619da4cc6d653bb5ab76f007 (diff) | |
| download | aoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.tar.gz aoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.tar.bz2 aoc-74b27ccca31bb757c737dd7fdc02f513f57561b2.zip | |
Merge remote-tracking branch 'origin/main'
Diffstat (limited to '2020/day1/threesum.pl')
| -rw-r--r-- | 2020/day1/threesum.pl | 44 |
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 @@ | |||
| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | use DDP; | ||
| 4 | # use Smart::Comments; | ||
| 5 | |||
| 6 | open my $fh, '<', "input" or die "no input present, $!"; | ||
| 7 | chomp(my @nums = <$fh>); | ||
| 8 | close $fh; | ||
| 9 | |||
| 10 | @nums = sort { $a <=> $b } @nums; | ||
| 11 | |||
| 12 | # fix one index, solve two sum problem | ||
| 13 | my $fixed_idx = 0; | ||
| 14 | my $l_idx = 1; | ||
| 15 | my $r_idx = $#nums; | ||
| 16 | |||
| 17 | my $total = $nums[$fixed_idx] + $nums[$l_idx] + $nums[$r_idx]; | ||
| 18 | |||
| 19 | while ($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 | |||
| 44 | print $nums[$fixed_idx] * $nums[$l_idx] * $nums[$r_idx]; | ||
