Two sum: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) m (→Functional: tweaks) |
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: tweaks to avoid warnings, show revised output) |
||
Line 1,436: | Line 1,436: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
<lang perl> |
<lang perl>use strict; |
||
use warnings; |
|||
use feature 'say'; |
|||
sub two_sum{ |
sub two_sum{ |
||
my |
my($sum,@numbers) = @_; |
||
my $num = shift; |
|||
my $i = 0; |
my $i = 0; |
||
my $j = $# |
my $j = $#numbers - 1; |
||
my @indices; |
|||
while ($i < $j) { |
while ($i < $j) { |
||
if ($ |
if ($numbers[$i] + $numbers[$j] == $sum) { push @indices, ($i, $j); $i++; } |
||
elsif ($numbers[$i] + $numbers[$j] < $sum) { $i++ } |
|||
else { $j-- } |
|||
} |
|||
if ($arr[$i] + $arr[$j] < $num) { |
|||
$i += 1; |
|||
} |
|||
else { |
|||
$j -= 1; |
|||
return; |
|||
} |
|||
} |
} |
||
return @indices |
|||
} |
} |
||
my @numbers = <0 2 11 19 90>; |
|||
⚫ | |||
say join ', ', @indices || 'No match'; |
|||
@indices = two_sum(25, @numbers); |
|||
say join ', ', @indices || 'No match';</lang> |
|||
⚫ | |||
{{out}} |
|||
print "$n1 $n2\n"; |
|||
<pre>1, 3 |
|||
($n1, $n2) = two_sum(\@numbers, 25); |
|||
No match</pre> |
|||
print "$n1 $n2\n"; |
|||
</lang> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |