Page 1 of 1

2 elements in an array, that add up to a given amount

Posted: Sat Jun 10, 2023 12:46 am
by HGAutomator
Hi,

The idea is to pass the values of a field into an array, and then try every pair of elements, to see if their sum compares to a target amount.


So if the target amount is 7, and the array is

{
4,
9,
2,
18,
3
}

, the pair { 4, 3 } would be returned, because they sum up to 7.

I know how to do it, based on google searches. But I was wondering if there was anything in HMG or some native Harbour functions that make this look easier or more elegant.

Re: 2 elements in an array, that add up to a given amount

Posted: Sat Jun 10, 2023 4:05 am
by AUGE_OHR
hi,

just a Idea :idea: (not Tested)

Code: Select all

LOCAL nInput := 7, nMax := nInput -1, nMin := 1

aArray :=   ASort( aArray,,, {|c1,c2| c1 > c2 } ) 
nPosi := ASCAN(aArray,{|x| x <= nMax} )
IF nPosi > 0
   nMax := aArray[nPosi]
   nMin := nInput - nMax

   aArray := ASort( aArray ) 
   nPosi := ASCAN(aArray,{|x| x >= nMin } )
   IF nPosi > 0
      nMin := aArray[nPosi]
      IF nInput = (nMax + nMin)

Re: 2 elements in an array, that add up to a given amount

Posted: Sat Jun 10, 2023 11:36 am
by branislavmil
Hello,
first idea:
t:=7

aniz:={4,9,2,18,3,5, 1,7,0}
ares:={}

for j=1 to len(aniz)
r:=aniz[j]
for k=j to len(aniz)
if r+aniz[k]=t .and. r<>0 .and. aniz[k]<>0
aadd(ares, {r, aniz[k]})
endif
next
next

for j=1 to len(ares)
? ares[j,1],ares[j,2]
next

Re: 2 elements in an array, that add up to a given amount

Posted: Sat Jun 10, 2023 3:47 pm
by HGAutomator
Hi Auge_ohr & branis,

Yep, that's pretty much the way I would approach it. I thought there might be some existing functions that perform parts of this.

Thanks.