Two sum: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 22:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F two_sum(arr, num)
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))</langsyntaxhighlight>
 
{{out}}
Line 45:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintArray(INT ARRAY a INT len)
INT i
 
Line 98:
Test(a,5,22)
Test(b,11,21)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Two_sum.png Screenshot from Atari 8-bit computer]
Line 116:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer i, u, v;
index x;
list l;
Line 128:
break;
}
}</langsyntaxhighlight>
{{Out}}
<pre>1 3</pre>
Line 134:
=={{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 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] #</langsyntaxhighlight>
{{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">
<lang APL>
⎕io ← 0 ⍝ sets index origin to 0
ts ← {⊃⍸ ⍵= 0.1@(⍸∘.=⍨⍳≢⍺) ∘.+⍨ ⍺}
⎕ ← 0 2 11 19 90 ts 21 ⍝ should be 1 3
</syntaxhighlight>
</lang>
{{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 :-)
 
<langsyntaxhighlight AppleScriptlang="applescript">-------------------------- TWO SUM -------------------------
 
-- twoSum :: Int -> [Int] -> [(Int, Int)]
Line 358:
end repeat
return lst
end zip</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang AppleScript="applescript">{{1, 3}}</langsyntaxhighlight>
----
 
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.
 
<langsyntaxhighlight lang="applescript">on twoSum(givenNumbers, givenSum)
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.</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|Arturo}}==
 
<langsyntaxhighlight lang="rebol">twoSum: function [numbers, s][
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]</langsyntaxhighlight>
 
{{out}}
Line 419:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">TwoSum(a, target){
i := 1, j := a.MaxIndex()
while(i < j){
Line 430:
}
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 460:
return("[]")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 468:
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">>000pv
>&:0\`#v_00g:1+00p6p
v >$&50p110p020p
Line 483:
>:#,_@ 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 493:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
 
Line 515:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 522:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 554:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1, 3</pre>
Line 560:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <tuple>
Line 594:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>{1,3}</pre>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 636:
 
return [];
}</langsyntaxhighlight>
{{out}}
<pre>[1, 3]</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="text">
main() {
var a = [1,2,3,4,5];
Line 670:
 
 
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{Trans|Python}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Two_Sum;
 
Line 712:
Writeln('(', i, ',', j, ')');
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 718:
</pre>
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
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)</langsyntaxhighlight>
 
{{out}}
Line 742:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{out}}
<pre>
Line 760:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators fry kernel locals math prettyprint sequences ;
IN: rosetta-code.two-sum
 
Line 773:
x y = { } { x y } ? ;
{ 21 55 11 } [ '[ { 0 2 11 19 90 } _ two-sum . ] call ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 783:
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
<langsyntaxhighlight lang="forth">CREATE A CELL ALLOT
: A[] ( n -- A[n]) CELLS A @ + @ ;
:NONAME 1- ;
Line 806:
TEST1 3 TWOSUM CR
TEST1 8 TWOSUM CR
BYE</langsyntaxhighlight>
{{out}}
<pre>[1, 3]
Line 814:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program twosum
implicit none
 
Line 839:
 
end program twosum
</syntaxhighlight>
</lang>
 
{{out}}
Line 845:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' "a" is the array of sorted non-negative integers
Line 885:
Print
Print "Press any number to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 894:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 930:
fmt.Println("The numbers with indices", p1, "and", p2, "sum to", targetSum)
}
}</langsyntaxhighlight>
 
{{out}}
Line 939:
=={{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 953:
| otherwise = sol xs $ dropWhile ((num <).(+x).fst) vs
 
main = print $ twoSum 21 [0, 2, 11, 19, 90]</langsyntaxhighlight>
{{out}}
<pre>[1,3]</pre>
Line 960:
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
Line 973:
 
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
Line 985:
main :: IO ()
main = mapM_ print $ sumTo 21 [0, 2, 11, 19, 90, 10]</langsyntaxhighlight>
{{Out}}
<pre>(1,3)
Line 996:
<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 1,026:
}
return []
end</langsyntaxhighlight>
 
{{out}}
Line 1,038:
 
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 1,087:
└───┘
;{.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 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.)
 
<langsyntaxhighlight Jlang="j">two_sum=:dyad define
sums=. +/~ y
matches=. x = sums
Line 1,115:
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 1,134:
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,144:
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,183:
return null;
}
}</langsyntaxhighlight>
<pre>[1, 3]</pre>
 
Line 1,197:
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,212:
}(21, [0, 2, 11, 19, 90]);
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[1,3]]</langsyntaxhighlight>
 
===ES6===
Line 1,221:
Composing a solution from generic functions like zip, bind (>>=, or flip concatMap) etc.
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,271:
sumTwo(21, [0, 2, 11, 19, 90, 10])
);
})();</langsyntaxhighlight>
{{Out}}
<pre>[[1,3],[2,5]]</pre>
Line 1,277:
=={{header|Jsish}}==
Based on Javascript entry.
<langsyntaxhighlight lang="javascript">/* Two Sum, in Jsish */
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]];</langsyntaxhighlight>
 
{{out}}
Line 1,311:
'''Works with gojq, the Go implementation of jq.
{{trans|Julia}}
<langsyntaxhighlight lang="jq">def twosum($s):
. as $v
| {i: 0, j: ($v|length - 1) }
Line 1,322:
[0, 2, 11, 19, 90]
| (twosum(21), twosum(25))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,332:
{{works with|Julia|0.6}}
{{trans|Python}}
<langsyntaxhighlight lang="julia">function twosum(v::Vector, s)
i = 1
j = length(v)
Line 1,347:
end
 
@show twosum([0, 2, 11, 19, 90], 21)</langsyntaxhighlight>
 
{{out}}
Line 1,353:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
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")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,389:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="liberty basic">myArray(0) = 0
myArray(1) = 2
myArray(2) = 11
Line 1,414:
Wend
twoToSum$ = "[]"
End Function</langsyntaxhighlight>
{{out}}
<pre>[1,3]</pre>
Line 1,420:
=={{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,435:
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,456:
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.
Line 1,463:
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="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</langsyntaxhighlight>
 
{{out}}<pre>
Line 1,475:
 
=={{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,486:
end function
 
print twoSum([0, 2, 11, 19, 90], 21)</langsyntaxhighlight>
 
Output:
Line 1,492:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE TwoSum;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 1,537:
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
Line 1,573:
 
 
main()</langsyntaxhighlight>
 
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class TwoSum {
function : Main(args : String[]) ~ Nil {
sum := 21;
Line 1,619:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,629:
{{trans|C}}
 
<langsyntaxhighlight lang="ocaml">let get_sums ~numbers ~sum =
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</langsyntaxhighlight>
 
Will return all possible sums, not just the first one found.
Line 1,660:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">a=.array~of( -5, 26, 0, 2, 11, 19, 90)
x=21
n=0
Line 1,672:
End
If n=0 Then
Say '[] - no items found' </langsyntaxhighlight>
{{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 ).
<langsyntaxhighlight lang="pascal">program twosum;
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 1,794:
else
writeln('No solution found');
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,808:
=={{header|Perl}}==
{{trans|Python}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,830:
 
@indices = two_sum(25, @numbers);
say join(', ', @indices) || 'No match';</langsyntaxhighlight>
{{out}}
<pre>1, 3
Line 1,836:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
{{trans|Raku}}
<!--<langsyntaxhighlight Phixlang="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;">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>
<!--</langsyntaxhighlight>-->
{{Out}}
Phix uses 1-based indexes
Line 1,870:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def two_sum /# arr num -- n #/
Line 1,891:
( 0 2 11 19 90 )
21 two_sum ?
25 two_sum ?</langsyntaxhighlight>
{{out}}
<pre>[2, 19]
Line 1,899:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de twosum (Lst N)
(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) )</langsyntaxhighlight>
{{out}}
<pre>(2 . 4) NIL (3 . 4)</pre>
Line 1,915:
=={{header|PowerShell}}==
Lazy, '''very''' lazy.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$numbers = @(0, 2, 11, 19, 90)
$sum = 21
Line 1,941:
Expression = { @($_.FirstIndex, $_.SecondIndex) }
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,951:
=={{header|Python}}==
{{trans|Raku}}
<langsyntaxhighlight lang="python">def two_sum(arr, num):
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))</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 2,054:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="python">'''Finding two integers that sum to a target value.'''
 
from itertools import chain
Line 2,130:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 peek ] is first ( [ --> n )
 
[ -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</langsyntaxhighlight>
 
{{out}}
Line 2,183:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
(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)))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,205:
===Procedural===
{{trans|zkl}}
<syntaxhighlight lang="raku" perl6line>sub two_sum ( @numbers, $sum ) {
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;</langsyntaxhighlight>
{{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" 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,253:
say two-sum-rl(@a, $_);
say two-sum-lr(@a, $_);
}</langsyntaxhighlight>
{{out}}
<pre>(1 3)
Line 2,262:
=={{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,282:
Say '[] - no items found'
Else
Say z 'solutions found'</langsyntaxhighlight>
{{out}}
<pre>[0,1] -5 26 21
Line 2,302:
 
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,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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,371:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Two Sum
 
Line 2,391:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,400:
 
=={{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,409:
numbers = [0, 2, 11, 19, 90]
p two_sum(numbers, 21)
p two_sum(numbers, 25)</langsyntaxhighlight>
 
{{out}}
Line 2,418:
 
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,426:
end
[]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::cmp::Ordering;
use std::ops::Add;
 
Line 2,459:
 
println!("{:?}", two_sum(&arr, sum));
}</langsyntaxhighlight>
 
{{out}}
Line 2,467:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.util
 
object TwoSum extends App {
Line 2,483:
}
 
}</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,501:
 
say two_sum([0, 2, 11, 19, 90], 21)
say two_sum([0, 2, 11, 19, 90], 25)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,510:
=={{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,525:
+---------+
1 | 2 4 |
+---------+</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight Valalang="vala">void main() {
int arr[] = { 0, 2, 11, 19, 90 }, sum = 21, i, j, check = 0;
Line 2,542:
if (check == 0)
print("[]");
}</langsyntaxhighlight>
{{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,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</langsyntaxhighlight>
{{out}}
<pre>
Line 2,586:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function TwoSum(numbers As Integer(), sum As Integer) As Integer()
Line 2,610:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>1, 3</pre>
Line 2,616:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">fn two_sum(a []int, target_sum int) (int, int, bool) {
len := a.len
if len < 2 {
Line 2,648:
println("The numbers with indices $p1 and $p2 sum to $target_sum")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,658:
{{trans|Python}}
{{works with|nasm}}
<langsyntaxhighlight lang="asm">
section .data
outputArr dd 0,0,0
Line 2,700:
mov eax, outputArr ;address of outputArr is returned in eax
ret
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var twosum = Fn.new { |a, n|
var c = a.count
if (c < 2) return []
Line 2,726:
}
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,741:
=={{header|XPL0}}==
Test cases from Algol 68.
<langsyntaxhighlight XPL0lang="xpl0">proc TwoSum(Size, Array, Sum);
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]
]</langsyntaxhighlight>
 
{{out}}
Line 2,769:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Two_sum
// by Galileo, 04/2022
Line 2,805:
Else
Print "The numbers with indices ", b(1), " and ", b(2), " sum to ", targetSum
End If</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="zkl">fcn twoSum(sum,ns){
i,j:=0,ns.len()-1;
while(i<j){
Line 2,819:
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,828:
</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>
10,333

edits