Two sum: Difference between revisions
Content added Content deleted
(→{{header|J}}: alternative approach for retrieving indicies) |
m (→{{header|REXX}}: added REXX version two.) |
||
Line 779: | Line 779: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
|||
<lang rexx>list=0 2 11 19 90 |
<lang rexx>list=0 2 11 19 90 |
||
Do i=0 By 1 Until list='' |
Do i=0 By 1 Until list='' |
||
Line 803: | Line 804: | ||
{{out}} |
{{out}} |
||
<pre>[1,3]</pre> |
<pre>[1,3]</pre> |
||
===version 2=== |
|||
This REXX version uses optimization in using integers that take advantage |
|||
that the numbers are an ordered list of positive integers. |
|||
All solutions are listed (if any). |
|||
If the list isn't an ordered list of positive integers, then |
|||
the '''while''' clause (below) should be removed, and then this REXX |
|||
version will work with any list (including negative numbers and also with any |
|||
real number. |
|||
<lang rexx>/*REXX pgm find 2 integers in a ordered list of positive integers that sum to a number. */ |
|||
list=0 2 11 19 90 ; say 'order list: ' list " (using a zero index.)" |
|||
sum=21 ; say 'target sum: ' sum |
|||
do #=0 for words(list) while word(list, #+1)<=sum /*only use possibles.*/ |
|||
@.#=word(list, #+1) |
|||
end /*#*/ |
|||
say /* [↓] look for sum of 2 int = the sum*/ |
|||
do a=0 for # /*scan up to the last possible integer.*/ |
|||
do b=a+1 to #-1; if @.a+@.b==sum then say 'a solution: ['a"," b']' |
|||
end /*y*/ /* [↑] 2 elements sum to target? Tell*/ |
|||
end /*x*/ /*stick a fork in it, we're all done. */</lang> |
|||
'''output''' |
|||
<pre> |
|||
order list: 0 2 11 19 90 (using a zero index.) |
|||
target sum: 21 |
|||
a solution: [1, 3] |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |