Two sum: Difference between revisions
Content added Content deleted
(Added Unicon, though this would look better if it suspended all solutions and not simply returning the first) |
|||
Line 161: | Line 161: | ||
[1, 3] |
[1, 3] |
||
[] |
[] |
||
</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
|||
{{Trans|Lua}} |
|||
Icon and Unicon are ordinal languages, first index is one. |
|||
<tt>fullimag</tt> library used to pretty print lists. |
|||
<lang unicon># |
|||
# twosum.icn, find two array elements that add up to a given sum |
|||
# Dedicated to the public domain |
|||
# |
|||
link fullimag |
|||
procedure main(arglist) |
|||
sum := pop(arglist) | 21 |
|||
L := [] |
|||
if *arglist > 0 then every put(L, integer(!arglist)) & L := sort(L) |
|||
else L := [0, 2, 11, 19, 90] |
|||
write(sum) |
|||
write(fullimage(L)) |
|||
write(fullimage(twosum(sum, L))) |
|||
end |
|||
# assume sorted list, only interested in zero or one solution |
|||
procedure twosum(sum, L) |
|||
i := 1 |
|||
j := *L |
|||
while i < j do { |
|||
try := L[i] + L[j] |
|||
if try = sum then return [i,j] |
|||
else |
|||
if try < sum then |
|||
i +:= 1 |
|||
else |
|||
j -:= 1 |
|||
} |
|||
return [] |
|||
end</lang> |
|||
{{out}} |
|||
<pre>$ unicon -s twosum.icn -x |
|||
21 |
|||
[0,2,11,19,90] |
|||
[2,4] |
|||
</pre> |
</pre> |
||