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.
2 elements in an array, that add up to a given amount
Moderator: Rathinagiri
-
- Posts: 197
- Joined: Thu Jul 16, 2020 5:42 pm
- DBs Used: DBF
- 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
hi,
just a Idea
(not Tested)
just a Idea

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
Jimmy
-
- 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
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
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
-
- 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
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.
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.