Two sum: Difference between revisions

32,091 bytes added ,  3 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎AppleScript :: Functional: Updated output for updated input list.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(36 intermediate revisions by 26 users not shown)
Line 1:
{{draftDraft task|Arithmetic operations}}
 
 
Line 18:
[http://stackoverflow.com/questions/8334981/find-pair-of-numbers-in-array-that-add-to-given-sum Stack Overflow: Find pair of numbers in array that add to given sum]
<br/><br/>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F two_sum(arr, num)
V i = 0
V j = arr.len - 1
L i < j
I arr[i] + arr[j] == num
R [i, j]
I arr[i] + arr[j] < num
i++
E
j--
R [Int]()
 
V numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))</syntaxhighlight>
 
{{out}}
<pre>
[1, 3]
[]
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program twosum64.s */
 
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Result : ["
szMessResult1: .asciz ","
szMessResult2: .asciz "]\n"
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "No soluce ! \n"
 
tabArray: .quad 0, 2, 11, 19, 90
.equ TABARRAYSIZE, (. - tabArray) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
sZoneConv1: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x0,qAdrtabArray
mov x1,#21
bl rechTwoNumbers
cmp x0,#-1 // no soluce
beq 100f
mov x2,x1
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
strb wzr,[x1,x0]
mov x0,x2
ldr x1,qAdrsZoneConv1
bl conversion10 // decimal conversion
strb wzr,[x1,x0]
mov x0,#5 // number string to display
ldr x1,qAdrszMessResult
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszMessResult1
ldr x4,qAdrsZoneConv1
ldr x5,qAdrszMessResult2
stp x5,x4,[sp,-16]! // save registers
bl displayStrings // display message
add sp,sp,#16
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneConv1: .quad sZoneConv1
qAdrszMessResult: .quad szMessResult
qAdrszMessResult1: .quad szMessResult1
qAdrszMessResult2: .quad szMessResult2
qAdrszMessErreur: .quad szMessErreur
qAdrszMessStart: .quad szMessStart
qAdrtabArray: .quad tabArray
/******************************************************************/
/* search two numbers to sum */
/******************************************************************/
/* x0 array addressr */
/* x1 sum */
/* x0 return first index */
/* x1 return second index */
rechTwoNumbers:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
stp x5,x6,[sp,-16]! // save registers
stp x7,x8,[sp,-16]! // save registers
mov x3,#0 // init result
1: // loop
ldr x4,[x0,x3,lsl #3] // load first number
mov x5,x3 // indice2
2:
ldr x6,[x0,x5,lsl #3] // load 2th number
add x7,x6,x4 // add the two numbers
cmp x7,x1 // equal to origin
beq 3f // yes -> ok
add x5,x5,#1 // increment indice2
cmp x5,#TABARRAYSIZE // end ?
blt 2b // no -> loop
add x3,x3,#1 // increment indice1
cmp x3,#TABARRAYSIZE - 1 // end ?
blt 1b // no loop
// not found
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,#-1
mov x1,#-1
b 100f // end
3:
mov x0,x3 // return results
mov x1,x5
100:
ldp x7,x8,[sp],16 // restaur registers
ldp x5,x6,[sp],16 // restaur registers
ldp x3,x4,[sp],16 // restaur registers
ldp x2,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* display multi strings */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: // INFO: displayStrings
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
add fp,sp,#48 // save paraméters address (6 registers saved * 8 bytes)
mov x4,x0 // save strings number
cmp x4,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x4,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x4,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x4,#3
ble 100f
mov x3,#3
sub x2,x4,#4
1: // loop extract address string on stack
ldr x0,[fp,x2,lsl #3]
bl affichageMess
subs x2,x2,#1
bge 1b
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Result : [1,3]
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT len)
INT i
 
Put('[)
FOR i=0 TO len-1
DO
PrintI(a(i))
IF i<len-1 THEN
Put(' )
FI
OD
Put(']) PutE()
RETURN
 
PROC PrintPairs(INT ARRAY a INT len,sum)
INT i,j,p1,p2,s,count
 
count=0
FOR i=0 TO len-2
DO
p1=a(i)
FOR j=i+1 TO len-1
DO
p2=a(j)
s=p1+p2
IF s=sum THEN
PrintF("(%I,%I) ",i,j)
count==+1
ELSEIF s>sum THEN
EXIT
FI
OD
OD
IF count=0 THEN
Print("none")
FI
PutE()
RETURN
 
PROC Test(INT ARRAY a INT len,sum)
Print("Array: ") PrintArray(a,len)
Print("Sum: ") PrintIE(sum)
Print("Pairs: ") PrintPairs(a,len,sum)
PutE()
RETURN
 
PROC Main()
INT ARRAY a=[0 2 11 19 90]
INT ARRAY b=[0 2 3 3 4 11 17 17 18 19 90]
 
Test(a,5,21)
Test(a,5,22)
Test(b,11,21)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Two_sum.png Screenshot from Atari 8-bit computer]
<pre>
Array: [0 2 11 19 90]
Sum: 21
Pairs: (1,3)
 
Array: [0 2 11 19 90]
Sum: 22
Pairs: none
 
Array: [0 2 3 3 4 11 17 17 18 19 90]
Sum: 21
Pairs: (1,9) (2,8) (3,8) (4,6) (4,7)
</pre>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer i, u, v;
index x;
list l;
Line 32 ⟶ 295:
break;
}
}</langsyntaxhighlight>
{{Out}}
<pre>1 3</pre>
Line 38 ⟶ 301:
=={{header|ALGOL 68}}==
{{trans|Lua}}
<langsyntaxhighlight lang="algol68"># returns the subscripts of a pair of numbers in a that sum to sum, a is assumed to be sorted #
# if there isn't a pair of numbers that summs to sum, an empty array is returned #
PRIO TWOSUM = 9;
Line 74 ⟶ 337:
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] #</langsyntaxhighlight>
{{out}}
<pre>
Line 81 ⟶ 344:
[]
[2, 3]
</pre>
 
=={{header|APL}}==
Works with [[Dyalog APL]].
 
∘.+⍨ ⍺ makes a table that is the outer sum of the left argument (the numbers).
 
We want to remove the diagonal, to avoid edge cases. We can achieve this by setting all these numbers to an arbitrary decimal value, since two integers can't sum to a decimal.
 
≢⍺ is the length of the numbers. ⍳≢⍺ creates an array from 0 to the length of the numbers. ∘.=⍳≢⍺ returns an identity matrix of size ≢⍺
(using the outer product with the equality function). ⍸ returns the indices of these numbers. 0.1@ sets that list to 0.1.
 
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>
1 3
</pre>
 
Line 95 ⟶ 379:
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 :-)
 
<langsyntaxhighlight AppleScriptlang="applescript">-------------------------- TWO SUM -------------------------
 
-- twoSum :: Int -> [Int] -> [(Int, Int)]
Line 241 ⟶ 525:
end repeat
return lst
end zip</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang AppleScript="applescript">{{1, 3}}</langsyntaxhighlight>
----
 
Line 249 ⟶ 533:
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.
 
<langsyntaxhighlight lang="applescript">on twoSum(givenNumbers, givenSum)
script o
property lst : givenNumbers
Line 271 ⟶ 555:
end twoSum
 
-- Test code:
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.</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{{2, 4}}
{}
{{1, 11}, {2, 8}, {2, 9}, {2, 10}, {3, 8}, {3, 9}, {3, 10}, {4, 7}, {5, 6}}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program twosum.s */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Result : ["
szMessResult1: .asciz ","
szMessResult2: .asciz "]\n"
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
szMessErreur: .asciz "No soluce ! \n"
 
tabArray: .int 0, 2, 11, 19, 90
.equ TABARRAYSIZE, (. - tabArray) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
sZoneConv1: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrtabArray
mov r1,#21
bl rechTwoNumbers
cmp r0,#-1 @ no soluce
beq 100f
mov r2,r1
ldr r1,iAdrsZoneConv
bl conversion10 @ decimal conversion
mov r3,#0
strb r3,[r1,r0]
mov r0,r2
ldr r1,iAdrsZoneConv1
bl conversion10 @ decimal conversion
mov r3,#0
strb r3,[r1,r0]
mov r0,#5 @ number string to display
ldr r1,iAdrszMessResult
ldr r2,iAdrsZoneConv @ insert conversion in message
ldr r3,iAdrszMessResult1
ldr r4,iAdrsZoneConv1
push {r4}
ldr r4,iAdrszMessResult2
push {r4}
bl displayStrings @ display message
add sp,#8
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrsZoneConv1: .int sZoneConv1
iAdrszMessResult: .int szMessResult
iAdrszMessResult1: .int szMessResult1
iAdrszMessResult2: .int szMessResult2
iAdrszMessErreur: .int szMessErreur
iAdrszMessStart: .int szMessStart
iAdrtabArray: .int tabArray
/******************************************************************/
/* search two numbers from sum */
/******************************************************************/
/* r0 array addressr */
/* r1 sum */
/* r0 return fist index */
/* r1 return second index */
rechTwoNumbers:
push {r2-r7,lr} @ save registers
mov r3,#0 @ init result
1: @ loop
ldr r4,[r0,r3,lsl #2] @ load first number
mov r5,r3 @ indice2
2:
ldr r6,[r0,r5,lsl #2] @ load 2th number
add r7,r6,r4 @ add the two numbers
cmp r7,r1 @ equal to origin
beq 3f @ yes -> ok
add r5,r5,#1 @ increment indice2
cmp r5,#TABARRAYSIZE @ end ?
blt 2b @ no -> loop
add r3,r3,#1 @ increment indice1
cmp r3,#TABARRAYSIZE - 1 @ end ?
blt 1b @ no loop
@ not found
ldr r0,iAdrszMessErreur
bl affichageMess
mov r0,#-1
mov r1,#-1
b 100f @ end
3:
mov r0,r3 @ return results
mov r1,r5
100:
pop {r2-r7,pc}
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
 
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Result : [1,3]
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">twoSum: function [numbers, s][
loop.with:'i numbers 'x [
if not? null? j: <= index numbers s-x ->
return @[i j]
]
return []
]
 
nums: [0 2 11 19 90]
 
print ["twoSum 21:" twoSum nums 21]
print ["twoSum 25:" twoSum nums 25]</syntaxhighlight>
 
{{out}}
 
<pre>twoSum 21: [1 3]
twoSum 25: []</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">TwoSum(a, target){
i := 1, j := a.MaxIndex()
while(i < j){
Line 293 ⟶ 761:
}
return "not found"
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % TwoSum([0, 2, 11, 19, 90], 21) ; returns 2, 4 (first index is 1 not 0)</langsyntaxhighlight>
Outputs:<pre>2,4</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TWO_SUM.AWK
BEGIN {
Line 323 ⟶ 791:
return("[]")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 331 ⟶ 799:
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">>000pv
>&:0\`#v_00g:1+00p6p
v >$&50p110p020p
Line 346 ⟶ 814:
>:#,_@ 8
p
> ^</langsyntaxhighlight>
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 356 ⟶ 824:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
 
Line 378 ⟶ 846:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 385 ⟶ 853:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 417 ⟶ 885:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1, 3</pre>
Line 423 ⟶ 891:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <tuple>
Line 457 ⟶ 925:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>{1,3}</pre>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 499 ⟶ 967:
 
return [];
}</langsyntaxhighlight>
{{out}}
<pre>[1, 3]</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="text">
main() {
var a = [1,2,3,4,5];
Line 533 ⟶ 1,001:
 
 
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{Trans|Python}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Two_Sum;
 
Line 575 ⟶ 1,043:
Writeln('(', i, ',', j, ')');
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
(1,3)
</pre>
 
=={{header|EasyLang}}==
EasyLang arrays are one-based, so the indices returned are also one-based.
<syntaxhighlight lang="easylang">
proc twoSum sum . array[] pair[] .
i = 1
j = len array[]
pair[] = [ ]
repeat
if array[i] + array[j] = sum
pair[] = [ i j ]
return
elif array[i] + array[j] > sum
j -= 1
elif array[i] + array[j] < sum
i += 1
.
until i = j
.
.
numbers[] = [ 0 2 11 19 90 ]
twoSum 21 numbers[] pair[]
print pair[]
</syntaxhighlight>
{{out}}
<pre>[ 2 4]</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def two_sum(numbers, sum) do
Enum.with_index(numbers) |>
Line 596 ⟶ 1,091:
numbers = [0, 2, 11, 19, 90]
IO.inspect RC.two_sum(numbers, 21)
IO.inspect RC.two_sum(numbers, 25)</langsyntaxhighlight>
 
{{out}}
Line 605 ⟶ 1,100:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Two Sum : Nigel Galloway December 5th., 2017
let fN n i =
Line 616 ⟶ 1,111:
fN n 0
printfn "%A" (fN [0; 2; 11; 19; 90] 21)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 623 ⟶ 1,118:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators fry kernel locals math prettyprint sequences ;
IN: rosetta-code.two-sum
 
Line 636 ⟶ 1,131:
x y = { } { x y } ? ;
{ 21 55 11 } [ '[ { 0 2 11 19 90 } _ two-sum . ] call ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 643 ⟶ 1,138:
{ 0 2 }
</pre>
 
A version that maintains a point-free style while still iterating over the numbers once:
 
<syntaxhighlight lang="factor">USING: accessors arrays assocs combinators.extras hashtables
kernel math math.combinatorics sequences ;
IN: rosetta-code.two-sum
 
DEFER: (two-sum)
TUPLE: helper sum seq index hash ;
 
: <two-sum-helper> ( sum seq -- helper )
\ helper new
swap [ >>seq ] keep length <hashtable> >>hash
swap >>sum 0 >>index ;
 
: no-sum ( helper -- empty ) drop { } ;
 
: in-bounds? ( helper -- ? )
[ index>> ] [ seq>> length ] bi < ;
 
: next-sum ( helper -- pair )
dup in-bounds? [ (two-sum) ] [ no-sum ] if ;
 
: next-index ( helper -- helper ) [ 1 + ] change-index ;
 
: result ( helper index -- helper ) swap index>> 2array ;
 
: find-compliment-index ( helper -- helper index/f )
dup [ sum>> ] [ index>> ] [ seq>> nth - ] [ ] quad hash>> at ;
 
: remember-item ( helper -- helper )
dup [ hash>> ] [ index>> ] [ seq>> nth ] [ index>> ]
quad set-of drop ;
 
: (two-sum) ( helper -- pair )
remember-item find-compliment-index
[ result ] [ next-index next-sum ] if* ;
 
: two-sum ( sum seq -- pair ) <two-sum-helper> (two-sum) ;
 
MAIN: [ { 21 55 11 } [ { 0 2 11 19 90 } two-sum . ] each ]
</syntaxhighlight>
 
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<langsyntaxhighlight lang="forth">CREATE A CELL ALLOT
: A[] ( n -- A[n]) CELLS A @ + @ ;
:NONAME 1- ;
Line 669 ⟶ 1,206:
TEST1 3 TWOSUM CR
TEST1 8 TWOSUM CR
BYE</langsyntaxhighlight>
{{out}}
<pre>[1, 3]
Line 677 ⟶ 1,214:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program twosum
implicit none
 
Line 702 ⟶ 1,239:
 
end program twosum
</syntaxhighlight>
</lang>
 
{{out}}
Line 708 ⟶ 1,245:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' "a" is the array of sorted non-negative integers
Line 748 ⟶ 1,285:
Print
Print "Press any number to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 757 ⟶ 1,294:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 793 ⟶ 1,330:
fmt.Println("The numbers with indices", p1, "and", p2, "sum to", targetSum)
}
}</langsyntaxhighlight>
 
{{out}}
Line 802 ⟶ 1,339:
=={{header|Haskell}}==
====Returning first match====
<langsyntaxhighlight Haskelllang="haskell">twoSum::(Num a,Ord a) => a -> [a] -> [Int]
twoSum num list = sol ls (reverse ls)
where
Line 816 ⟶ 1,353:
| otherwise = sol xs $ dropWhile ((num <).(+x).fst) vs
 
main = print $ twoSum 21 [0, 2, 11, 19, 90]</langsyntaxhighlight>
{{out}}
<pre>[1,3]</pre>
Line 823 ⟶ 1,360:
Listing multiple solutions (as zero-based indices) where they exist:
 
<langsyntaxhighlight lang="haskell">sumTo :: Int -> [Int] -> [(Int, Int)]
sumTo n ns =
let ixs = zip [0 ..] ns
in ixs >>=
>>= ( \(i, x) ->
drop (isucc + 1i) ixs >>=
>>= \(j, y) ->
[ (i, j)
| (x + y) == n ])
]
)
 
main :: IO ()
main = mapM_ print $ sumTo 21 [0, 2, 11, 19, 90, 10]</langsyntaxhighlight>
 
Or, resugaring a little – pulling more into the scope of the list comprehension:
<langsyntaxhighlight Haskelllang="haskell">sumTo :: Int -> [Int] -> [(Int, Int)]
sumTo n ns =
let ixs = zip [0 ..] ns
in [ (i, j)
| (i, x) <- ixs
, (j, y) <- drop (succ i + 1) ixs
, (x + y) == n ]
 
main :: IO ()
main = mapM_ print $ sumTo 21 [0, 2, 11, 19, 90, 10]</langsyntaxhighlight>
{{Out}}
<pre>(1,3)
Line 857 ⟶ 1,396:
<tt>fullimag</tt> library used to pretty print lists.
 
<langsyntaxhighlight lang="unicon">#
# twosum.icn, find two array elements that add up to a given sum
# Dedicated to the public domain
Line 887 ⟶ 1,426:
}
return []
end</langsyntaxhighlight>
 
{{out}}
Line 899 ⟶ 1,438:
 
So, first off, our basic approach will be to find the sums:
<langsyntaxhighlight Jlang="j"> =+/~0 2 11 19 90
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</langsyntaxhighlight>
 
And, check if any of them are our desired value:
<langsyntaxhighlight Jlang="j"> 21=+/~0 2 11 19 90
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</langsyntaxhighlight>
 
Except, we want indices here, so let's toss the structure so we can get those:
<langsyntaxhighlight Jlang="j"> ,21=+/~0 2 11 19 90
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</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight Jlang="j"> $21=+/~0 2 11 19 90
5 5
5 5#:I.,21=+/~0 2 11 19 90
1 3
3 1</langsyntaxhighlight>
 
Or, taking advantage of being able to use verbs to represent combining their results, when we use three of them:
<langsyntaxhighlight Jlang="j"> ($ #: I.@,)21=+/~0 2 11 19 90
1 3
3 1</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight Jlang="j"> ($ <@#: I.@,)21=+/~0 2 11 19 90
┌───┬───┐
│1 3│3 1│
Line 948 ⟶ 1,487:
└───┘
;{.a:,~($ <@#: I.@,)21=+/~0 2 11 19 90
1 3</langsyntaxhighlight>
 
Finally, let's start pulling our arguments out using that three verbs combining form:
 
<langsyntaxhighlight Jlang="j"> ;{.a:,~($ <@#: I.@,) 21([ = +/~@])0 2 11 19 90
1 3
;{.a:,~21 ($ <@#: I.@,)@([ = +/~@])0 2 11 19 90
1 3</langsyntaxhighlight>
 
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:
<langsyntaxhighlight Jlang="j"> ;{. 21 (a:,~ ($ <@#: I.@,)@([ = +/~@]))0 2 11 19 90
1 3</langsyntaxhighlight>
 
And, let's finish the job, give this a name, and test it out:
<langsyntaxhighlight Jlang="j"> twosum=: ;@{.@(a:,~ ($ <@#: I.@,)@([ = +/~@]))
21 twosum 0 2 11 19 90
1 3</langsyntaxhighlight>
 
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 970 ⟶ 1,509:
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.)
 
<langsyntaxhighlight Jlang="j">two_sum=:dyad define
sums=. +/~ y
matches=. x = sums
Line 976 ⟶ 1,515:
pair_inds=. ($matches) #: sum_inds
; {. a: ,~ <"1 pair_inds
)</langsyntaxhighlight>
 
And, testing:
 
<langsyntaxhighlight Jlang="j"> 21 two_sum 0 2 11 19 90
1 3</langsyntaxhighlight>
 
Or, we could go slightly more traditional and instead of doing that boxing at the end, use an if/else statement:
 
<langsyntaxhighlight Jlang="j">two_sum=:dyad define
sums=. +/~ y
matches=. x = sums
Line 995 ⟶ 1,534:
i.0
end.
)</langsyntaxhighlight>
 
Then again, most people don't read J anyways, so maybe just stick with the earlier implementation:
 
<langsyntaxhighlight Jlang="j">twosum=: ;@{.@(a:,~ ($ <@#: I.@,)@([ = +/~@]))</langsyntaxhighlight>
 
'''Alternative approach'''
Line 1,005 ⟶ 1,544:
An alternative method for identifying and returning non-duplicate indicies of the pairs follows.
 
<langsyntaxhighlight lang="j"> 21 (= +/~) 0 2 11 19 90
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</langsyntaxhighlight>
The array is symmetrical so we can zero one half to remove duplicate pairs and then retrieve the remaining indicies using sparse array functionality.
<langsyntaxhighlight lang="j">zeroLowerTri=: * [: </~ i.@#
getIdx=: 4 $. $.
twosum_alt=: getIdx@zeroLowerTri@(= +/~)</langsyntaxhighlight>
 
Testing ...
<langsyntaxhighlight lang="j"> 21 twosum_alt 0 2 11 19 90
1 3</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Lua}}
<langsyntaxhighlight lang="java">import java.util.Arrays;
 
public class TwoSum {
Line 1,044 ⟶ 1,583:
return null;
}
}</langsyntaxhighlight>
<pre>[1, 3]</pre>
 
Line 1,058 ⟶ 1,597:
in the map result are eliminated by the concat.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
var concatMap = function (f, xs) {
return [].concat.apply([], xs.map(f))
Line 1,073 ⟶ 1,612:
}(21, [0, 2, 11, 19, 90]);
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[1,3]]</langsyntaxhighlight>
 
===ES6===
Line 1,082 ⟶ 1,621:
Composing a solution from generic functions like zip, bind (>>=, or flip concatMap) etc.
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,132 ⟶ 1,671:
sumTwo(21, [0, 2, 11, 19, 90, 10])
);
})();</langsyntaxhighlight>
{{Out}}
<pre>[[1,3],[2,5]]</pre>
Line 1,138 ⟶ 1,677:
=={{header|Jsish}}==
Based on Javascript entry.
<langsyntaxhighlight lang="javascript">/* Two Sum, in Jsish */
function twoSum(target, list) {
var concatMap = function (f, xs) {
Line 1,159 ⟶ 1,698:
;twoSum(21, list);
;list[twoSum(21, list)[0][0]];
;list[twoSum(21, list)[0][1]];</langsyntaxhighlight>
 
{{out}}
Line 1,167 ⟶ 1,706:
list[twoSum(21, list)[0][0]] ==> 2
list[twoSum(21, list)[0][1]] ==> 19</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq.
{{trans|Julia}}
<syntaxhighlight lang="jq">def twosum($s):
. as $v
| {i: 0, j: ($v|length - 1) }
| until( .i >= .j or $v[.i] + $v[.j] == $s;
if $v[.i] + $v[.j] < $s then .i += 1
else .j -= 1
end)
| if .i >= .j then [] else [.[]] end ; # as required
 
[0, 2, 11, 19, 90]
| (twosum(21), twosum(25))
</syntaxhighlight>
{{out}}
<pre>
[1,3]
[]
</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{trans|Python}}
<langsyntaxhighlight lang="julia">function twosum(v::Vector, s)
i = 1
j = length(v)
Line 1,186 ⟶ 1,747:
end
 
@show twosum([0, 2, 11, 19, 90], 21)</langsyntaxhighlight>
 
{{out}}
Line 1,192 ⟶ 1,753:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? {
Line 1,220 ⟶ 1,781:
println("The numbers with indices ${p.first} and ${p.second} sum to $targetSum")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,787:
The numbers with indices 1 and 3 sum to 21
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="liberty basic">myArray(0) = 0
myArray(1) = 2
myArray(2) = 11
myArray(3) = 19
myArray(4) = 90
 
sum = 21
 
Print twoToSum$("myArray", sum, 0, 4)
End
 
Function twoToSum$(arrayName$, targetSum, minElement, maxElement)
i = minElement : j = maxElement
While (i < j)
Select Case
Case (Eval(arrayName$;"(";i;")") + Eval(arrayName$;"(";j;")")) < targetSum
i = (i + 1)
Case (Eval(arrayName$;"(";i;")") + Eval(arrayName$;"(";j;")")) > targetSum
j = (j - 1)
Case Else
twoToSum$ = "[";i;",";j;"]"
Exit Function
End Select
Wend
twoToSum$ = "[]"
End Function</syntaxhighlight>
{{out}}
<pre>[1,3]</pre>
 
=={{header|Lua}}==
Lua uses one-based indexing.
<langsyntaxhighlight lang="lua">function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
Line 1,244 ⟶ 1,835:
end
 
print(table.concat(twoSum({0,2,11,19,90}, 21), ","))</langsyntaxhighlight>
{{out}}
<pre>2,4</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">two_sum := proc(arr, sum)
local i,j,temp:
i,j := 1,numelems(arr):
Line 1,265 ⟶ 1,856:
end proc:
L := Array([0,2,2,11,19,19,90]);
two_sum(L, 21);</langsyntaxhighlight>
{{Out|Output}}
Note that Maple does 1 based indexing.
<pre>
[2,5]
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">twoSum[data_List, sum_] :=
Block[{indices = Subsets[Range@Length@data, {2}]},
Cases[indices, _?(Total@data[[#]] == sum &)]]
 
twoSum[{0, 2, 11, 19, 90}, 21] // TableForm</syntaxhighlight>
 
{{out}}<pre>
2 4
Note, indexing in Mathematica starts at 1
</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">twoSum = function(numbers, sum)
// 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,284 ⟶ 1,886:
end function
 
print twoSum([0, 2, 11, 19, 90], 21)</langsyntaxhighlight>
 
Output:
Line 1,290 ⟶ 1,892:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE TwoSum;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 1,335 ⟶ 1,937:
WriteString(buf);
ReadChar;
END TwoSum.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc twoSum (src : openarray[int], target : int ) : array[2, int] =
if src.len < 2:
return
 
for base in 0 .. (src.len - 2):
for ext in (base + 1) .. < src.len:
if (src[base] + src[ext]) == target:
result[0] = base
result[1] = ext
Line 1,371 ⟶ 1,973:
 
 
main()</langsyntaxhighlight>
 
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class TwoSum {
function : Main(args : String[]) ~ Nil {
sum := 21;
Line 1,417 ⟶ 2,019:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,427 ⟶ 2,029:
{{trans|C}}
 
<langsyntaxhighlight lang="ocaml">let get_sums ~numbers ~sum =
let n = Array.length numbers in
let res = ref [] in
Line 1,447 ⟶ 2,049:
List.iter (fun (i, j) ->
Printf.printf "# Found: %d %d\n" i j
) res</langsyntaxhighlight>
 
Will return all possible sums, not just the first one found.
Line 1,458 ⟶ 2,060:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">a=.array~of( -5, 26, 0, 2, 11, 19, 90)
x=21
n=0
Line 1,470 ⟶ 2,072:
End
If n=0 Then
Say '[] - no items found' </langsyntaxhighlight>
{{out}}
<pre>[0,1]
Line 1,477 ⟶ 2,079:
=={{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 ).
<langsyntaxhighlight lang="pascal">program twosum;
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 1,592 ⟶ 2,194:
else
writeln('No solution found');
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,606 ⟶ 2,208:
=={{header|Perl}}==
{{trans|Python}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,628 ⟶ 2,230:
 
@indices = two_sum(25, @numbers);
say join(', ', @indices) || 'No match';</langsyntaxhighlight>
{{out}}
<pre>1, 3
Line 1,634 ⟶ 2,236:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>function twosum(sequence s, integer t)
<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>
for i=1 to length(s) do
<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>
for j=i+1 to length(s) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</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>
if s[i]+s[j]=t then
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">t</span> <span style="color: #008080;">then</span>
return {i,j}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">}</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return {}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?twosum({0, 2, 11, 19, 90},21)</lang>
<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>
<!--</syntaxhighlight>-->
{{trans|Raku}}
<!--<syntaxhighlight lang="phix">-->
<lang Phix>function twosum(sequence numbers, integer total)
<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>
integer i=1, j=length(numbers)
<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>
while i<j do
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #000000;">j</span> <span style="color: #008080;">do</span>
switch compare(numbers[i]+numbers[j],total) do
<span style="color: #008080;">switch</span> <span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">total</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
case -1: i += 1
<span style="color: #008080;">case</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
case 0: return {i, j}
<span style="color: #008080;">case</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">:</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">}</span>
case +1: j -= 1
<span style="color: #008080;">case</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: #000000;">1</span>
end switch
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return {}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
{{Out}}
Phix uses 1-based indexes
Line 1,664 ⟶ 2,270:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def two_sum /# arr num -- n #/
Line 1,685 ⟶ 2,291:
( 0 2 11 19 90 )
21 two_sum ?
25 two_sum ?</langsyntaxhighlight>
{{out}}
<pre>[2, 19]
Line 1,693 ⟶ 2,299:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de twosum (Lst N)
(for ((I . A) Lst A (cdr A))
(T
Line 1,703 ⟶ 2,309:
(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) )</langsyntaxhighlight>
{{out}}
<pre>(2 . 4) NIL (3 . 4)</pre>
Line 1,709 ⟶ 2,315:
=={{header|PowerShell}}==
Lazy, '''very''' lazy.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$numbers = @(0, 2, 11, 19, 90)
$sum = 21
Line 1,735 ⟶ 2,341:
Expression = { @($_.FirstIndex, $_.SecondIndex) }
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,745 ⟶ 2,351:
=={{header|Python}}==
{{trans|Raku}}
<langsyntaxhighlight lang="python">def two_sum(arr, num):
i = 0
j = len(arr) - 1
Line 1,760 ⟶ 2,366:
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))</langsyntaxhighlight>
 
or, in terms of '''itertools.product''':
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Finding two integers that sum to a target value.'''
 
from itertools import (product)
Line 1,848 ⟶ 2,454:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>The indices of any two integers drawn from [0, 2, 11, 19, 90, 10]
Line 1,873 ⟶ 2,479:
or, a little more parsimoniously (not generating the entire cartesian product), in terms of '''concatMap''':
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Finding two integers that sum to a target value.'''
 
from itertools import chain
Line 1,924 ⟶ 2,530:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[(1, 3), (2, 5)]
[]</pre>
 
=={{header|Quackery}}==
 
So… I initially misread the task as "return the two integers" and then realised it was "…the indices of…", but that's OK — it just meant writing an extra word to find the indices, given the numbers.
 
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.
 
<syntaxhighlight lang="quackery"> [ 0 peek ] is first ( [ --> n )
 
[ -1 peek ] is last ( [ --> n )
 
[ 1 split nip ] is top ( [ --> [ )
 
[ -1 split drop ] is tail ( [ --> [ )
 
[ temp put
[ dup size 2 < iff
[ drop [] ] done
dup first over last +
temp share -
dup 0 = iff
[ drop dup first
swap last join ] done
0 < iff top else tail
again ]
temp release ] is twosum ( [ n --> [ )
 
[ over temp put
twosum
[] swap
witheach
[ temp share find join ]
temp release
dup [] != if
[ dup unpack = if
[ behead 1+ join ] ] ] is task ( [ n --> [ )
 
' [ 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</syntaxhighlight>
 
{{out}}
 
<pre>[ 1 3 ]
[ ]
[ 2 3 ]
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
(define (two-sum v m)
(let inr ((l 0) (r (sub1 (vector-length v))))
Line 1,945 ⟶ 2,598:
(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)))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,952 ⟶ 2,605:
===Procedural===
{{trans|zkl}}
<syntaxhighlight lang="raku" perl6line>sub two_sum ( @numbers, $sum ) {
die '@numbers is not sorted' unless [<=] @numbers;
 
Line 1,967 ⟶ 2,620:
 
say two_sum ( 0, 2, 11, 19, 90 ), 21;
say two_sum ( 0, 2, 11, 19, 90 ), 25;</langsyntaxhighlight>
{{out}}
<pre>(1 3)
Line 1,975 ⟶ 2,628:
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" perl6line>sub two-sum-lr (@a, $sum) {
# (((^@a X ^@a) Z=> (@a X+ @a)).grep($sum == *.value)>>.keys.map:{ .split(' ').sort.join(' ')}).unique
(
Line 2,000 ⟶ 2,653:
say two-sum-rl(@a, $_);
say two-sum-lr(@a, $_);
}</langsyntaxhighlight>
{{out}}
<pre>(1 3)
Line 2,009 ⟶ 2,662:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX */
list='-5 26 0 2 11 19 90'
Do i=0 By 1 Until list=''
Line 2,029 ⟶ 2,682:
Say '[] - no items found'
Else
Say z 'solutions found'</langsyntaxhighlight>
{{out}}
<pre>[0,1] -5 26 21
Line 2,042 ⟶ 2,695:
The list of numbers can be in any format, &nbsp; not just integers. &nbsp; Also, they need not be unique.
 
The list of integers need &nbsp; needn''not''t &nbsp; be sorted.
 
A &nbsp; '''numeric digits 500''' &nbsp; statement was added just in case some rather largehumongous numbers were entered.
 
No verification was performed to ensure that all items in the list were numeric.
 
A little extra code was added to have the output columns aligned.
<langsyntaxhighlight lang="rexx">/*REXX program finds two numbers in a list of numbers that sum to a particular target.*/
numeric digits 500 /*be able to handle some larger numbers*/
parse arg targ list /*obtain optional arguments from the CL*/
Line 2,056 ⟶ 2,709:
say 'the list: ' list /*echo the list to the terminal*/
say 'the target sum: ' targ /* " " target sum " " " */
w= 0; sol= 0 /*width; # of solutions found (so far)*/
@solution= 'a solution: zero─based indices ' /*a SAY literal for space conservation.*/
sol=0; w=0 /*number of solutions found (so far). */
do #=0 for words(list); _=word(list, #+1) /*examine the list, construct an array.*/
@.#= _; w= max(w, length(_) ) /*assign a number to an indexed array. */
end /*#*/ /*W: the maximum width of any number. */
L= length(#) /*L: " " " " " index. */
@solution= 'a solution: zero─based indices ' /*a SAY literal for space conservation.*/
say /* [↓] look for sum of 2 numbers=target*/
do a=0 for # /*scan up to the last number in array. */
do b=a+1 to #-1; if @.a + @.b\=targ then iterate /*is sumSum not correct? Skip.*/
sol= sol + 1 /*bump count of the number of solutions*/
say @solution center( "["right(a, L)',' right(b, L)"]", L+L+5) ,
right(@.a, w*4) " + " right(@.b, w) ' = ' targ
end /*b*/ /*show the 2 indices and the summation.*/
end /*a*/
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,118 ⟶ 2,771:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Two Sum
 
Line 2,138 ⟶ 2,791:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,144 ⟶ 2,797:
target sum: 21
a solution: [1 3]
</pre>
 
=={{header|RPL}}==
≪ → array sum
≪ { }
1 array SIZE '''FOR''' j
array j 0 PUT
sum array j GET -
'''IF''' POS '''THEN'''
j LAST
'''IF''' DUP2 > '''THEN''' SWAP '''END'''
R→C
'''IF''' DUP2 POS '''THEN''' DROP '''ELSE''' + '''END'''
'''END NEXT'''
≫ ≫ ‘<span style="color:blue">TWOSUM</span>’ STO
 
{0 2 11 19 90} 21 <span style="color:blue">TWOSUM</span>
{0 2 11 19 90} 22 <span style="color:blue">TWOSUM</span>
{0 2 3 3 4 11 17 17 18 19 90} 21 <span style="color:blue">TWOSUM</span>
{{out}}
<pre>
3: { (2,4) }
2: { }
1: { (2,10) (3,9) (4,9) (5,7) (5,8) }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def two_sum(numbers, sum)
numbers.each_with_index do |x,i|
if j = numbers.index(sum - x) then return [i,j] end
Line 2,156 ⟶ 2,833:
numbers = [0, 2, 11, 19, 90]
p two_sum(numbers, 21)
p two_sum(numbers, 25)</langsyntaxhighlight>
 
{{out}}
Line 2,165 ⟶ 2,842:
 
When the size of the Array is bigger, the following is more suitable.
<langsyntaxhighlight lang="ruby">def two_sum(numbers, sum)
numbers.each_with_index do |x,i|
key = sum - x
Line 2,173 ⟶ 2,850:
end
[]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::cmp::Ordering;
use std::ops::Add;
 
Line 2,206 ⟶ 2,883:
 
println!("{:?}", two_sum(&arr, sum));
}</langsyntaxhighlight>
 
{{out}}
Line 2,214 ⟶ 2,891:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.util
 
object TwoSum extends App {
Line 2,230 ⟶ 2,907:
}
 
}</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="ruby">func two_sum(numbers, sum) {
var (i, j) = (0, numbers.end)
while (i < j) {
Line 2,248 ⟶ 2,925:
 
say two_sum([0, 2, 11, 19, 90], 21)
say two_sum([0, 2, 11, 19, 90], 25)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,257 ⟶ 2,934:
=={{header|Stata}}==
Notice that array indexes start at 1 in Stata.
<langsyntaxhighlight lang="stata">function find(a, x) {
i = 1
j = length(a)
Line 2,272 ⟶ 2,949:
+---------+
1 | 2 4 |
+---------+</langsyntaxhighlight>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
int arr[] = { 0, 2, 11, 19, 90 }, sum = 21, i, j, check = 0;
for (i = 0; i < 4; i++) {
for ( j = i+1; j < 5; j++) {
if (arr[i] + arr[j] == sum) {
print("[%d,%d]",i,j);
check = 1;
break;
}
}
}
if (check == 0)
print("[]");
}</syntaxhighlight>
{{out}}
<pre>[1,3]</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
Function two_sum(a As Variant, t As Integer) As Variant
Dim i, j As Integer
Line 2,302 ⟶ 2,998:
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</langsyntaxhighlight>
{{out}}
<pre>
Line 2,314 ⟶ 3,010:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function TwoSum(numbers As Integer(), sum As Integer) As Integer()
Line 2,338 ⟶ 3,034:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>1, 3</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">
fn two_sum(a []int, target_sum int) (int, int, bool) {
len := a.len
if len < 2 {return 0, 0, false}
for i in 0..len - 1 {
if a[i] <= target_sum {
for j in i + 1..len {
sum := a[i] + a[j]
if sum == target_sum {return i, j, true}
if sum > target_sum {break}
}
}
else {break}
}
return 0, 0, false
}
fn main() {
a := [0, 2, 11, 19, 90]
target_sum := 21
p1, p2, ok := two_sum(a, target_sum)
if !ok {println("No two numbers were found whose sum is $target_sum")}
else {println("The numbers with indices $p1 and $p2 sum to $target_sum")}
}
</syntaxhighlight>
 
{{out}}
<pre>
The numbers with indices 1 and 3 sum to 21
</pre>
 
=={{header|X86 Assembly}}==
{{trans|Python}}
{{works with|nasm}}
<langsyntaxhighlight lang="asm">
section .data
outputArr dd 0,0,0
Line 2,387 ⟶ 3,116:
mov eax, outputArr ;address of outputArr is returned in eax
ret
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var twosum = Fn.new { |a, n|
var c = a.count
if (c < 2) return []
Line 2,413 ⟶ 3,142:
}
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,424 ⟶ 3,153:
 
Indices: [0, 4] sum to 90 (0 + 90 = 90)
</pre>
 
=={{header|XPL0}}==
Test cases from Algol 68.
<syntaxhighlight lang="xpl0">proc TwoSum(Size, Array, Sum);
int Size, Array, Sum, I, J;
[Text(0, "[");
for I:= 0 to Size-1 do
for J:= I+1 to Size-1 do
if Array(I) + Array(J) = Sum then
[IntOut(0, I); Text(0, ", "); IntOut(0, J);
J:= Size; I:= Size;
];
Text(0, "]^m^j");
];
 
[TwoSum(5, [ 0, 2, 11, 19, 90], 21); \ should be [1, 3]
TwoSum(7, [-8, -2, 0, 1, 5, 8, 11], 3); \ should be [0, 6] (or [1, 4])
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]
]</syntaxhighlight>
 
{{out}}
<pre>
[1, 3]
[0, 6]
[]
[2, 3]
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Two_sum
// by Galileo, 04/2022
Sub twoSum (a(), b(), targetSum)
local ub, sum, i, j
ub = arraysize(a(), 1)
For i = 1 To ub - 1
If a(i) <= targetSum Then
For j = i + 1 To ub
sum = a(i) + a(j)
If sum = targetSum Then
Redim b(2)
b(1) = i : b(2) = j
Return
ElsIf sum > targetSum Then
break
EndIf
Next j
Else
break
EndIf
Next i
End Sub
Dim a(5)
Dim b(1)
data 0, 2, 11, 19, 90
for n = 1 to 5 : read a(n) : next
targetSum = 21
twoSum(a(), b(), targetSum)
If arraysize(b(), 1) = 1 Then
Print "No two numbers were found whose sum is ", targetSum
Else
Print "The numbers with indices ", b(1), " and ", b(2), " sum to ", targetSum
End If</syntaxhighlight>
{{out}}
<pre>The numbers with indices 2 and 4 sum to 21
---Program done, press RETURN---</pre>
=={{header|Zig}}==
 
'''Works with:''' 0.11.x, 0.12.0-dev.1389+42d4d07ef
 
<syntaxhighlight lang="zig">pub fn sumsUpTo(comptime T: type, input: []const T, target_sum: T) ?struct { usize, usize } {
if (input.len <= 1) return null;
 
return result: for (input[0 .. input.len - 1], 0..) |left, left_i| {
if (left > target_sum) break :result null;
 
const offset = left_i + 1;
for (input[offset..], offset..) |right, right_i| {
const current_sum = left + right;
if (current_sum < target_sum) continue;
if (current_sum == target_sum) break :result .{ left_i, right_i };
if (current_sum > target_sum) break;
}
} else null;
}</syntaxhighlight>
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
 
const stderr = std.io.getStdErr();
const stderr_w = stderr.writer();
 
const a = [_]u32{ 0, 2, 11, 19, 90 };
const target_sum: u32 = 21;
 
const optional_indexes = sumsUpTo(u32, &a, target_sum);
if (optional_indexes) |indexes| {
try stdout_w.print("Result: [{d}, {d}].\n", .{ indexes[0], indexes[1] });
} else {
try stderr_w.print("Numbers with sum {d} were not found!\n", .{target_sum});
}
}</syntaxhighlight>
 
{{Out}}
<pre>
Result: [1, 3].
</pre>
 
=={{header|zkl}}==
The sorted O(n) no external storage solution:
<langsyntaxhighlight lang="zkl">fcn twoSum(sum,ns){
i,j:=0,ns.len()-1;
while(i<j){
Line 2,435 ⟶ 3,279:
else if(s>sum) j-=1;
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">twoSum2(21,T(0,2,11,19,90)).println();
twoSum2(25,T(0,2,11,19,90)).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 2,444 ⟶ 3,288:
</pre>
The unsorted O(n!) all solutions solution:
<langsyntaxhighlight lang="zkl">fcn twoSum2(sum,ns){
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)) })
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">twoSum2(21,T(0,2,11,19,90,21)).println();
twoSum2(25,T(0,2,11,19,90,21)).println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits