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

General Help regarding HMG, Compilation, Linking, Samples

Moderator: Rathinagiri

Post Reply
HGAutomator
Posts: 197
Joined: Thu Jul 16, 2020 5:42 pm
DBs Used: DBF

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

Post 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.
User avatar
AUGE_OHR
Posts: 2093
Joined: Sun Aug 25, 2019 3:12 pm
DBs Used: DBF, PostgreSQL, MySQL, SQLite
Location: Hamburg, Germany

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

Post 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)
have fun
Jimmy
branislavmil
Posts: 10
Joined: Sat Sep 29, 2018 3:36 pm
DBs Used: DBF

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

Post 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
HGAutomator
Posts: 197
Joined: Thu Jul 16, 2020 5:42 pm
DBs Used: DBF

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

Post 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.
Post Reply