Two sum: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 22:
{{trans|Python}}
<
V i = 0
V j = arr.len - 1
Line 36:
V numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))</
{{out}}
Line 45:
=={{header|Action!}}==
<
INT i
Line 98:
Test(a,5,22)
Test(b,11,21)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Two_sum.png Screenshot from Atari 8-bit computer]
Line 116:
=={{header|Aime}}==
<
index x;
list l;
Line 128:
break;
}
}</
{{Out}}
<pre>1 3</pre>
Line 134:
=={{header|ALGOL 68}}==
{{trans|Lua}}
<
# if there isn't a pair of numbers that summs to sum, an empty array is returned #
PRIO TWOSUM = 9;
Line 170:
print twosum( ( -8, -2, 0, 1, 5, 8, 11 ), 3 ); # should be [0, 6] (or [1, 4]) #
print twosum( ( -3, -2, 0, 1, 5, 8, 11 ), 17 ); # should be [] #
print twosum( ( -8, -2, -1, 1, 5, 9, 11 ), 0 ) # should be [2, 3] #</
{{out}}
<pre>
Line 190:
Then, we just need to find where the right argument (the target) is equal to the matrix, get the indices, and return the first one (⊃).
<syntaxhighlight lang="apl">
⎕io ← 0 ⍝ sets index origin to 0
ts ← {⊃⍸ ⍵= 0.1@(⍸∘.=⍨⍳≢⍺) ∘.+⍨ ⍺}
⎕ ← 0 2 11 19 90 ts 21 ⍝ should be 1 3
</syntaxhighlight>
{{out}}
<pre>
Line 212:
AppleScript, unusually, happens to make internal use of one-based indices, rigid adherence to which would, of course, in this case, simply produce the wrong result :-)
<
-- twoSum :: Int -> [Int] -> [(Int, Int)]
Line 358:
end repeat
return lst
end zip</
{{Out}}
<syntaxhighlight lang
----
Line 366:
Like the "Functional" script above, this returns multiple solutions when they're found. However it assumes a sorted list, as per the clarified task description, which allows some optimisation of the search. Also, the indices returned are 1-based, which is the AppleScript norm.
<
script o
property lst : givenNumbers
Line 391:
twoSum({0, 2, 11, 19, 90}, 21) -- Task-specified list.
twoSum({0, 3, 11, 19, 90}, 21) -- No matches.
twoSum({-44, 0, 0, 2, 10, 11, 19, 21, 21, 21, 65, 90}, 21) -- Multiple solutions.</
{{output}}
<
{}
{{1, 11}, {2, 8}, {2, 9}, {2, 10}, {3, 8}, {3, 9}, {3, 10}, {4, 7}, {5, 6}}</
=={{header|Arturo}}==
<
loop.with:'i numbers 'x [
if not? null? j: <= index numbers s-x ->
Line 411:
print ["twoSum 21:" twoSum nums 21]
print ["twoSum 25:" twoSum nums 25]</
{{out}}
Line 419:
=={{header|AutoHotkey}}==
<
i := 1, j := a.MaxIndex()
while(i < j){
Line 430:
}
return "not found"
}</
Examples:<
Outputs:<pre>2,4</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TWO_SUM.AWK
BEGIN {
Line 460:
return("[]")
}
</syntaxhighlight>
{{out}}
<pre>
Line 468:
=={{header|Befunge}}==
<
>&:0\`#v_00g:1+00p6p
v >$&50p110p020p
Line 483:
>:#,_@ 8
p
> ^</
There are a couple of caveats due to limitations of the language. The target cannot be above 127, there can be no more than 47 elements in the list and the list must be delimited by a negative number before the target value as follows:
<pre>
Line 493:
=={{header|C}}==
<syntaxhighlight lang="c">
#include<stdio.h>
Line 515:
return 0;
}
</syntaxhighlight>
Output :
<pre>
Line 522:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 554:
}
}
</syntaxhighlight>
{{out}}
<pre>1, 3</pre>
Line 560:
=={{header|C++}}==
{{trans|C#}}
<
#include <map>
#include <tuple>
Line 594:
return 0;
}</
{{out}}
<pre>{1,3}</pre>
=={{header|D}}==
<
void main() {
Line 636:
return [];
}</
{{out}}
<pre>[1, 3]</pre>
=={{header|Dart}}==
<syntaxhighlight lang="text">
main() {
var a = [1,2,3,4,5];
Line 670:
</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{Trans|Python}}
<syntaxhighlight lang="delphi">
program Two_Sum;
Line 712:
Writeln('(', i, ',', j, ')');
Readln;
end.</
{{out}}
<pre>
Line 718:
</pre>
=={{header|Elixir}}==
<
def two_sum(numbers, sum) do
Enum.with_index(numbers) |>
Line 733:
numbers = [0, 2, 11, 19, 90]
IO.inspect RC.two_sum(numbers, 21)
IO.inspect RC.two_sum(numbers, 25)</
{{out}}
Line 742:
=={{header|F_Sharp|F#}}==
<
// Two Sum : Nigel Galloway December 5th., 2017
let fN n i =
Line 753:
fN n 0
printfn "%A" (fN [0; 2; 11; 19; 90] 21)
</syntaxhighlight>
{{out}}
<pre>
Line 760:
=={{header|Factor}}==
<
IN: rosetta-code.two-sum
Line 773:
x y = { } { x y } ? ;
{ 21 55 11 } [ '[ { 0 2 11 19 90 } _ two-sum . ] call ] each</
{{out}}
<pre>
Line 783:
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<
: A[] ( n -- A[n]) CELLS A @ + @ ;
:NONAME 1- ;
Line 806:
TEST1 3 TWOSUM CR
TEST1 8 TWOSUM CR
BYE</
{{out}}
<pre>[1, 3]
Line 814:
=={{header|Fortran}}==
<
implicit none
Line 839:
end program twosum
</syntaxhighlight>
{{out}}
Line 845:
=={{header|FreeBASIC}}==
<
' "a" is the array of sorted non-negative integers
Line 885:
Print
Print "Press any number to quit"
Sleep</
{{out}}
Line 894:
=={{header|Go}}==
{{trans|Kotlin}}
<
import "fmt"
Line 930:
fmt.Println("The numbers with indices", p1, "and", p2, "sum to", targetSum)
}
}</
{{out}}
Line 939:
=={{header|Haskell}}==
====Returning first match====
<
twoSum num list = sol ls (reverse ls)
where
Line 953:
| otherwise = sol xs $ dropWhile ((num <).(+x).fst) vs
main = print $ twoSum 21 [0, 2, 11, 19, 90]</
{{out}}
<pre>[1,3]</pre>
Line 960:
Listing multiple solutions (as zero-based indices) where they exist:
<
sumTo n ns =
let ixs = zip [0 ..] ns
Line 973:
main :: IO ()
main = mapM_ print $ sumTo 21 [0, 2, 11, 19, 90, 10]</
Or, resugaring a little – pulling more into the scope of the list comprehension:
<
sumTo n ns =
let ixs = zip [0 ..] ns
Line 985:
main :: IO ()
main = mapM_ print $ sumTo 21 [0, 2, 11, 19, 90, 10]</
{{Out}}
<pre>(1,3)
Line 996:
<tt>fullimag</tt> library used to pretty print lists.
<
# twosum.icn, find two array elements that add up to a given sum
# Dedicated to the public domain
Line 1,026:
}
return []
end</
{{out}}
Line 1,038:
So, first off, our basic approach will be to find the sums:
<
0 2 11 19 90
2 4 13 21 92
11 13 22 30 101
19 21 30 38 109
90 92 101 109 180</
And, check if any of them are our desired value:
<
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0</
Except, we want indices here, so let's toss the structure so we can get those:
<
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
I.,21=+/~0 2 11 19 90
8 16</
Except, we really needed that structure - in this case, since we had a five by five table, we want to interpret this result as a base five pair of numbers:
<
5 5
5 5#:I.,21=+/~0 2 11 19 90
1 3
3 1</
Or, taking advantage of being able to use verbs to represent combining their results, when we use three of them:
<
1 3
3 1</
But to be more like the other task implementations here, we don't want all the results, we just want zero or one result. We can't just take the first result, though, because that would fill in a 0 0 result if there were none, and 0 0 could have been a valid result which does not make sense for the failure case. So, instead, let's package things up so we can add an empty to the end and take the first of those:
<
┌───┬───┐
│1 3│3 1│
Line 1,087:
└───┘
;{.a:,~($ <@#: I.@,)21=+/~0 2 11 19 90
1 3</
Finally, let's start pulling our arguments out using that three verbs combining form:
<
1 3
;{.a:,~21 ($ <@#: I.@,)@([ = +/~@])0 2 11 19 90
1 3</
a: is not a verb, but we can use a noun as the left verb of three as an implied constant verb whose result is itself:
<
1 3</
And, let's finish the job, give this a name, and test it out:
<
21 twosum 0 2 11 19 90
1 3</
Except that looks like a bit of a mess. A lot of the reason for this is that ascii is ugly to look at. (Another issue, though, is that a lot of people are not used to architecting control flow as expressions.)
Line 1,109:
So... let's do this over again, using a more traditional implementation where we name intermediate results. (We're going to stick with our architecture, though, because changing the architecture to the more traditional approach would change the space/time tradeoff to require more time.)
<
sums=. +/~ y
matches=. x = sums
Line 1,115:
pair_inds=. ($matches) #: sum_inds
; {. a: ,~ <"1 pair_inds
)</
And, testing:
<
1 3</
Or, we could go slightly more traditional and instead of doing that boxing at the end, use an if/else statement:
<
sums=. +/~ y
matches=. x = sums
Line 1,134:
i.0
end.
)</
Then again, most people don't read J anyways, so maybe just stick with the earlier implementation:
<
'''Alternative approach'''
Line 1,144:
An alternative method for identifying and returning non-duplicate indicies of the pairs follows.
<
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0</
The array is symmetrical so we can zero one half to remove duplicate pairs and then retrieve the remaining indicies using sparse array functionality.
<
getIdx=: 4 $. $.
twosum_alt=: getIdx@zeroLowerTri@(= +/~)</
Testing ...
<
1 3</
=={{header|Java}}==
{{trans|Lua}}
<
public class TwoSum {
Line 1,183:
return null;
}
}</
<pre>[1, 3]</pre>
Line 1,197:
in the map result are eliminated by the concat.
<
var concatMap = function (f, xs) {
return [].concat.apply([], xs.map(f))
Line 1,212:
}(21, [0, 2, 11, 19, 90]);
})();
</syntaxhighlight>
{{Out}}
<syntaxhighlight lang
===ES6===
Line 1,221:
Composing a solution from generic functions like zip, bind (>>=, or flip concatMap) etc.
{{Trans|Haskell}}
<
'use strict';
Line 1,271:
sumTwo(21, [0, 2, 11, 19, 90, 10])
);
})();</
{{Out}}
<pre>[[1,3],[2,5]]</pre>
Line 1,277:
=={{header|Jsish}}==
Based on Javascript entry.
<
function twoSum(target, list) {
var concatMap = function (f, xs) {
Line 1,298:
;twoSum(21, list);
;list[twoSum(21, list)[0][0]];
;list[twoSum(21, list)[0][1]];</
{{out}}
Line 1,311:
'''Works with gojq, the Go implementation of jq.
{{trans|Julia}}
<
. as $v
| {i: 0, j: ($v|length - 1) }
Line 1,322:
[0, 2, 11, 19, 90]
| (twosum(21), twosum(25))
</syntaxhighlight>
{{out}}
<pre>
Line 1,332:
{{works with|Julia|0.6}}
{{trans|Python}}
<
i = 1
j = length(v)
Line 1,347:
end
@show twosum([0, 2, 11, 19, 90], 21)</
{{out}}
Line 1,353:
=={{header|Kotlin}}==
<
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? {
Line 1,381:
println("The numbers with indices ${p.first} and ${p.second} sum to $targetSum")
}
}</
{{out}}
Line 1,389:
=={{header|Liberty BASIC}}==
<
myArray(1) = 2
myArray(2) = 11
Line 1,414:
Wend
twoToSum$ = "[]"
End Function</
{{out}}
<pre>[1,3]</pre>
Line 1,420:
=={{header|Lua}}==
Lua uses one-based indexing.
<
local i, j, s = 1, #numbers
while i < j do
Line 1,435:
end
print(table.concat(twoSum({0,2,11,19,90}, 21), ","))</
{{out}}
<pre>2,4</pre>
=={{header|Maple}}==
<
local i,j,temp:
i,j := 1,numelems(arr):
Line 1,456:
end proc:
L := Array([0,2,2,11,19,19,90]);
two_sum(L, 21);</
{{Out|Output}}
Note that Maple does 1 based indexing.
Line 1,463:
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Block[{indices = Subsets[Range@Length@data, {2}]},
Cases[indices, _?(Total@data[[#]] == sum &)]]
twoSum[{0, 2, 11, 19, 90}, 21] // TableForm</
{{out}}<pre>
Line 1,475:
=={{header|MiniScript}}==
<
// Make a map of values to their indices in the numbers array
// as we go, so we will know when we've found a match.
Line 1,486:
end function
print twoSum([0, 2, 11, 19, 90], 21)</
Output:
Line 1,492:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 1,537:
WriteString(buf);
ReadChar;
END TwoSum.</
=={{header|Nim}}==
<
if src.len < 2:
return
Line 1,573:
main()</
=={{header|Objeck}}==
{{trans|Java}}
<
function : Main(args : String[]) ~ Nil {
sum := 21;
Line 1,619:
}
}
</syntaxhighlight>
Output:
Line 1,629:
{{trans|C}}
<
let n = Array.length numbers in
let res = ref [] in
Line 1,649:
List.iter (fun (i, j) ->
Printf.printf "# Found: %d %d\n" i j
) res</
Will return all possible sums, not just the first one found.
Line 1,660:
=={{header|ooRexx}}==
<
x=21
n=0
Line 1,672:
End
If n=0 Then
Say '[] - no items found' </
{{out}}
<pre>[0,1]
Line 1,679:
=={{header|Pascal}}==
A little bit lengthy. Implemented an unsorted Version with quadratic runtime too and an extra test case with 83667 elements that needs 83667*86666/2 ~ 3.5 billion checks ( ~1 cpu-cycles/check, only if data in cache ).
<
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 1,794:
else
writeln('No solution found');
end.</
{{out}}
<pre>
Line 1,808:
=={{header|Perl}}==
{{trans|Python}}
<
use warnings;
use feature 'say';
Line 1,830:
@indices = two_sum(25, @numbers);
say join(', ', @indices) || 'No match';</
{{out}}
<pre>1, 3
Line 1,836:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">twosum</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
Line 1,848:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">twosum</span><span style="color: #0000FF;">({</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">11</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">19</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">90</span><span style="color: #0000FF;">},</span><span style="color: #000000;">21</span><span style="color: #0000FF;">)</span>
<!--</
{{trans|Raku}}
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">twosum</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">numbers</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">)</span>
Line 1,862:
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</
{{Out}}
Phix uses 1-based indexes
Line 1,870:
=={{header|Phixmonti}}==
<
def two_sum /# arr num -- n #/
Line 1,891:
( 0 2 11 19 90 )
21 two_sum ?
25 two_sum ?</
{{out}}
<pre>[2, 19]
Line 1,899:
=={{header|PicoLisp}}==
<
(for ((I . A) Lst A (cdr A))
(T
Line 1,909:
(twosum (0 2 11 19 90) 21)
(twosum (-3 -2 0 1 5 8 11) 17)
(twosum (-8 -2 -1 1 5 9 11) 0) )</
{{out}}
<pre>(2 . 4) NIL (3 . 4)</pre>
Line 1,915:
=={{header|PowerShell}}==
Lazy, '''very''' lazy.
<syntaxhighlight lang="powershell">
$numbers = @(0, 2, 11, 19, 90)
$sum = 21
Line 1,941:
Expression = { @($_.FirstIndex, $_.SecondIndex) }
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,951:
=={{header|Python}}==
{{trans|Raku}}
<
i = 0
j = len(arr) - 1
Line 1,966:
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))</
or, in terms of '''itertools.product''':
{{Works with|Python|3.7}}
<
from itertools import (product)
Line 2,054:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>The indices of any two integers drawn from [0, 2, 11, 19, 90, 10]
Line 2,079:
or, a little more parsimoniously (not generating the entire cartesian product), in terms of '''concatMap''':
{{Works with|Python|3.7}}
<
from itertools import chain
Line 2,130:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[(1, 3), (2, 5)]
Line 2,141:
The last three lines of <code>task</code> are in case the two integers found by <code>twosum</code> are equal - in which case, as <code>find</code> finds the first instance in the array and the array is sorted, we can safely take the index plus one as the second index.
<
[ -1 peek ] is last ( [ --> n )
Line 2,173:
' [ 0 2 11 19 20 ] 21 task echo cr
' [ 0 2 11 19 20 ] 25 task echo cr
' [ 0 2 12 12 20 ] 24 task echo cr</
{{out}}
Line 2,183:
=={{header|Racket}}==
<
(define (two-sum v m)
(let inr ((l 0) (r (sub1 (vector-length v))))
Line 2,198:
(check-equal? (two-sum #(-8 -2 0 1 5 8 11) 3) '(0 6))
(check-equal? (two-sum #(-3 -2 0 1 5 8 11) 17) #f)
(check-equal? (two-sum #(-8 -2 -1 1 5 9 11) 0) '(2 3)))</
=={{header|Raku}}==
Line 2,205:
===Procedural===
{{trans|zkl}}
<syntaxhighlight lang="raku"
die '@numbers is not sorted' unless [<=] @numbers;
Line 2,220:
say two_sum ( 0, 2, 11, 19, 90 ), 21;
say two_sum ( 0, 2, 11, 19, 90 ), 25;</
{{out}}
<pre>(1 3)
Line 2,228:
The two versions differ only in how 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).
<syntaxhighlight lang="raku"
# (((^@a X ^@a) Z=> (@a X+ @a)).grep($sum == *.value)>>.keys.map:{ .split(' ').sort.join(' ')}).unique
(
Line 2,253:
say two-sum-rl(@a, $_);
say two-sum-lr(@a, $_);
}</
{{out}}
<pre>(1 3)
Line 2,262:
=={{header|REXX}}==
===version 1===
<
list='-5 26 0 2 11 19 90'
Do i=0 By 1 Until list=''
Line 2,282:
Say '[] - no items found'
Else
Say z 'solutions found'</
{{out}}
<pre>[0,1] -5 26 21
Line 2,302:
A little extra code was added to have the output columns aligned.
<
numeric digits 500 /*be able to handle some larger numbers*/
parse arg targ list /*obtain optional arguments from the CL*/
Line 2,325:
say
if sol==0 then sol= 'None' /*prettify the number of solutions if 0*/
say 'number of solutions found: ' sol /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,371:
=={{header|Ring}}==
<
# Project : Two Sum
Line 2,391:
next
next
</syntaxhighlight>
Output:
<pre>
Line 2,400:
=={{header|Ruby}}==
<
numbers.each_with_index do |x,i|
if j = numbers.index(sum - x) then return [i,j] end
Line 2,409:
numbers = [0, 2, 11, 19, 90]
p two_sum(numbers, 21)
p two_sum(numbers, 25)</
{{out}}
Line 2,418:
When the size of the Array is bigger, the following is more suitable.
<
numbers.each_with_index do |x,i|
key = sum - x
Line 2,426:
end
[]
end</
=={{header|Rust}}==
<
use std::ops::Add;
Line 2,459:
println!("{:?}", two_sum(&arr, sum));
}</
{{out}}
Line 2,467:
=={{header|Scala}}==
<
object TwoSum extends App {
Line 2,483:
}
}</
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/GxVfCE7/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/S5aks2gRTcqcy1VUWJ6GzQ Scastie (JVM)].
=={{header|Sidef}}==
{{trans|Raku}}
<
var (i, j) = (0, numbers.end)
while (i < j) {
Line 2,501:
say two_sum([0, 2, 11, 19, 90], 21)
say two_sum([0, 2, 11, 19, 90], 25)</
{{out}}
<pre>
Line 2,510:
=={{header|Stata}}==
Notice that array indexes start at 1 in Stata.
<
i = 1
j = length(a)
Line 2,525:
+---------+
1 | 2 4 |
+---------+</
=={{header|Vala}}==
<
int arr[] = { 0, 2, 11, 19, 90 }, sum = 21, i, j, check = 0;
Line 2,542:
if (check == 0)
print("[]");
}</
{{out}}
<pre>[1,3]</pre>
=={{header|VBA}}==
<
Function two_sum(a As Variant, t As Integer) As Variant
Dim i, j As Integer
Line 2,574:
Call prnt(two_sum(Array(-3, -2, 0, 1, 5, 8, 11), 17))
Call prnt(two_sum(Array(-8, -2, -1, 1, 5, 9, 11), 0))
End Sub</
{{out}}
<pre>
Line 2,586:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function TwoSum(numbers As Integer(), sum As Integer) As Integer()
Line 2,610:
End Sub
End Module</
{{out}}
<pre>1, 3</pre>
Line 2,616:
=={{header|Vlang}}==
{{trans|Go}}
<
len := a.len
if len < 2 {
Line 2,648:
println("The numbers with indices $p1 and $p2 sum to $target_sum")
}
}</
{{out}}
Line 2,658:
{{trans|Python}}
{{works with|nasm}}
<
section .data
outputArr dd 0,0,0
Line 2,700:
mov eax, outputArr ;address of outputArr is returned in eax
ret
</syntaxhighlight>
=={{header|Wren}}==
<
var c = a.count
if (c < 2) return []
Line 2,726:
}
System.print()
}</
{{out}}
Line 2,741:
=={{header|XPL0}}==
Test cases from Algol 68.
<
int Size, Array, Sum, I, J;
[Text(0, "[");
Line 2,757:
TwoSum(7, [-3, -2, 0, 1, 5, 8, 11], 17); \ should be []
TwoSum(7, [-8, -2, -1, 1, 5, 9, 11], 0); \ should be [2, 3]
]</
{{out}}
Line 2,769:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
// by Galileo, 04/2022
Line 2,805:
Else
Print "The numbers with indices ", b(1), " and ", b(2), " sum to ", targetSum
End If</
{{out}}
<pre>The numbers with indices 2 and 4 sum to 21
Line 2,812:
=={{header|zkl}}==
The sorted O(n) no external storage solution:
<
i,j:=0,ns.len()-1;
while(i<j){
Line 2,819:
else if(s>sum) j-=1;
}
}</
<
twoSum2(25,T(0,2,11,19,90)).println();</
{{out}}
<pre>
Line 2,828:
</pre>
The unsorted O(n!) all solutions solution:
<
Utils.Helpers.combosKW(2,ns).filter('wrap([(a,b)]){ a+b==sum }) // lazy combos
.apply('wrap([(a,b)]){ return(ns.index(a),ns.index(b)) })
}</
<
twoSum2(25,T(0,2,11,19,90,21)).println();</
{{out}}
<pre>
|