Two sum: Difference between revisions

Content added Content deleted
(Added Sidef)
(Added FreeBASIC)
Line 161: Line 161:
[1, 3]
[1, 3]
[]
[]
</pre>

=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64

' "a" is the array of sorted non-negative integers
' "b" is the array to contain the result and is assumed to be empty initially
Sub twoSum (a() As UInteger, b() As Integer, targetSum As UInteger)
Dim lb As Integer = LBound(a)
Dim ub As Integer = UBound(a)
If ub = -1 Then Return '' empty array
Dim sum As UInteger

For i As Integer = lb To ub - 1
If a(i) <= targetSum Then
For j As Integer = i + 1 To ub
sum = a(i) + a(j)
If sum = targetSum Then
Redim b(0 To 1)
b(0) = i : b(1) = j
Return
ElseIf sum > targetSum Then
Exit For
End If
Next j
Else
Exit For
End If
Next i
End Sub

Dim a(0 To 4) As UInteger = {0, 2, 11, 19, 90}
Dim b() As Integer
Dim targetSum As UInteger = 21
twoSum a(), b(), targetSum
If UBound(b) = -1 Then
Print "No two numbers were found whose sum is "; targetSum
Else
Print "The numbers with indices"; b(LBound(b)); " and"; b(UBound(b)); " sum to "; targetSum
End If
Print
Print "Press any number to quit"
Sleep</lang>

{{out}}
<pre>
The numbers with indices 1 and 3 sum to 21
</pre>
</pre>