Jump to content

Two sum: Difference between revisions

→‎{{header|AppleScript}}: Added an idiomatic solution.
(→‎{{header|AppleScript}}: Added an idiomatic solution.)
Line 84:
 
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}
{{Trans|Haskell}}
Line 236 ⟶ 237:
{{Out}}
<lang AppleScript>{{1, 3}, {2, 5}}</lang>
----
===Idiomatic===
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.
 
<lang applescript>on twoSum(givenNumbers, givenSum)
script o
property lst : givenNumbers
property output : {}
end script
set listLength to (count o's lst)
repeat with i from 1 to (listLength - 1)
set n1 to item i of o's lst
repeat with j from (i + 1) to listLength
set thisSum to n1 + (item j of o's lst)
if (thisSum = givenSum) then
set end of o's output to {i, j}
else if (thisSum > givenSum) then
exit repeat
end if
end repeat
end repeat
return o's output
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.</lang>
 
{{output}}
<lang applescript>{{2, 4}}
{}
{{1, 11}, {2, 8}, {2, 9}, {2, 10}, {3, 8}, {3, 9}, {3, 10}, {4, 7}, {5, 6}}</lang>
 
=={{header|AutoHotkey}}==
557

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.