Anonymous user
Two sum: Difference between revisions
→version 2: updated the REXX program to handle the latest task requirements/specifications, used a template for the output, added a solution count (and message), added an aligned summation, indicated that solution contains (zero based) indices.
mNo edit summary |
(→version 2: updated the REXX program to handle the latest task requirements/specifications, used a template for the output, added a solution count (and message), added an aligned summation, indicated that solution contains (zero based) indices.) |
||
Line 1,272:
===version 2===
All solutions are listed (if any), along with a count of the number of solutions.
Also, it's mentioned that the indices are zero─based, and formatted solutions are shown.
<lang rexx>/*REXX
parse arg targ list /*obtain optional arguments from the CL*/
if targ='' | targ="," then targ= 21 /*Not specified? Then use the defaults*/
if list='' | list="," then list= 0 2 11 19 90
say 'the target sum: ' targ
@.#=_; w=max(w, length(_) ) /*assign a number to an indexed array. */
say /* [↓] look for sum of 2 numbers=target*/
do a=0 for # /*scan up to the last number in array. */
sol=sol+1 /*bump count of the number of solutions*/
say 'a solution: zero─based indices ['a"," b']' ,
' ' right(@.a, w) " + " right(@.b, w) ' = ' targ
end /*b*/ /*show the 2 indices and the summation.*/
say
if sol==0 then sols= 'None' /*prettify the number of solutions if 0*/
say 'number of solutions found: ' sol /*stick a fork in it, we're all done. */</lang>
{{out|output|text= when using the default inputs:}}
<pre>
the list: 0 2 11 19 90
the target sum: 21
a solution: zero─based indices [1, 3] 2 + 19 = 21
number of solutions found: 1
</pre>
{{out|output|text= when using the input of: 21 -78 -5 -4 -1 0 1 2 3 5 11 14 16 17 18 18 19 23 24 25 26 99}}
▲<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.)"
▲ do #=0 for words(list) while word(list, #+1)<=sum /*only use possibles.*/
▲ 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>
<pre>
the target sum: 21
a solution: zero─based indices [0, 20] -78 + 99 = 21
a solution: zero─based indices [1, 19] -5 + 26 = 21
a solution: zero─based indices [2, 18] -4 + 25 = 21
a solution: zero─based indices [6, 15] 2 + 19 = 21
a solution: zero─based indices [7, 13] 3 + 18 = 21
a solution: zero─based indices [7, 14] 3 + 18 = 21
a solution: zero─based indices [8, 11] 5 + 16 = 21
number of solutions found: 7
</pre>
|