Two sum: Difference between revisions

m
→‎{{header|REXX}}: added REXX version two.
(→‎{{header|J}}: alternative approach for retrieving indicies)
m (→‎{{header|REXX}}: added REXX version two.)
Line 779:
 
=={{header|REXX}}==
===version 1===
<lang rexx>list=0 2 11 19 90
Do i=0 By 1 Until list=''
Line 803 ⟶ 804:
{{out}}
<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 &nbsp; '''while''' &nbsp; clause (below) should be removed, &nbsp; and then this REXX
version will work with any list &nbsp; (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}}==