Two sum: Difference between revisions

→‎{{header|Perl 6}}: Added functional version
(→‎{{header|Python}}: concatMap version zip(*) in lieu of fst, snd)
(→‎{{header|Perl 6}}: Added functional version)
Line 1,473:
 
=={{header|Perl 6}}==
 
===Procedural===
{{trans|zkl}}
<lang perl6>sub two_sum ( @numbers, $sum ) {
Line 1,493 ⟶ 1,495:
<pre>(1 3)
Nil</pre>
 
===Functional===
The two versions differ only in one 'reads' the notional flow of processing: left-to-right versus right-to-left.
Both return all pairs that sum to the target value, not just the first (e.g. for input of <code>0 2 10 11 19 90</code> would get indices 1/4 and 2/3).
<lang perl6>sub two-sum-lr (@a, $sum) {
(
(
(^@a X ^@a) Z=> (@a X+ @a)
).grep($sum == *.value)>>.keys
.map:{ .split(' ').sort.join(' ')}
).unique
}
 
sub two-sum-rl (@a, $sum) {
unique
map {.split(' ').sort.join(' ')},
keys %(
grep {.value == $sum}, %(
(^@a X ^@a) Z=> (@a X[+] @a)
)
)
}
 
my @a = <0 2 11 19 90>;
for 21, 25 {
say two-sum-rl(@a, $_);
say two-sum-lr(@a, $_);
}</lang>
{{out}}
<pre>(1 3)
(1 3)
()
()</pre>
 
=={{header|Phix}}==
2,392

edits