See "leetcode perl solutions" for background. See https://leetcode.com/problems/two-sum/ for the problem.
Here's a quick solution I put together. Feel free to improve or discuss. Use of features from more recent Perls is fine (do indicate the version required). Use modules if you want. Golfing solutions are acceptable.
Update: I received feedback from ++LanX#11140763 and ++NetWallah#11140770 regarding issues with my original code. I made changes accordingly. I also noted that the issue identified by NetWallah, was also present in the next OUTER if $input->[$i] > $target; statement: I've removed that line and added two more tests (which also show that zero is a valid target). The new code follows. The original code can be found at the end in the spoiler.
#!/usr/bin/env perl use strict; use warnings; use constant { INPUT => 0, TARGET => 1, EXPECTED => 2, }; use Test::More; my @tests = ( [[2,7,11,15], 9, [0,1]], [[2,7,11,15], 9, [1,0]], [[3,2,4], 6, [1,2]], [[3,2,4], 6, [2,1]], [[3,3], 6, [0,1]], [[3,3], 6, [1,0]], [[-5,-3,1,4,7], 1, [1,3]], [[-5,-3,1,4,7], 1, [3,1]], [[1,-1], 0, [0,1]], [[1,-1], 0, [1,0]], ); plan tests => 0+@tests; for my $test (@tests) { is_deeply sort_arrayref(two_sum($test->[INPUT], $test->[TARGET])), sort_arrayref($test->[EXPECTED]); } sub two_sum { my ($input, $target) = @_; my $got; OUTER: for my $i (0 .. $#$input - 1) { for my $j ($i + 1 .. $#$input) { if ($input->[$i] + $input->[$j] == $target) { $got = [$i, $j]; last OUTER; } } } return $got; } sub sort_arrayref { my ($aref) = @_; return [ sort { $a <=> $b } @$aref ]; }
New output:
1..8 ok 1 ok 2 ok 3 ok 4 ok 5 ok 6 ok 7 ok 8 ok 9 ok 10
The original code and its output are in the spoiler. Note that this is code on which others' comments were based.
— Ken
In reply to LeetCode Problem #1 - Two Sum - Improve and/or discuss. by kcott
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |