Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IF statement w/ multiple conditions

Status
Not open for further replies.

gnomemock

Programmer
Oct 16, 2010
1
CA
I'm trying to create a union of two sets with no duplications. Array a contains n distinct integers. Array b contains m distinct integers. I want to find out the number of elements in the union before I place elements into the union array, so that I can allocate memory. Anyway, I want to count the number of elements in a that aren't in b as follows:
p=0
do i=1,n,1
if (a(i) /= b(j) for j = 1,..., & m) then
!i.e. a(i) /= b(1) .and. a(i) /= b(2) .and. ... a(i) /= b(m)
p = p+1
end if
end do

The problem is that I don't know how to code the above conditional statement so that it recognizes only elements of a that aren't in b. What kind of construct would work?
 
Use another loop :

Code:
logical :: equal
..
p=0
do i=1,n
  equal=.false.
  do j=1,m
    if(a(i) == b(j)) then
      equal=.true.
      exit
    endif
  enddo
  if(.not.equal) then
    p=p+1
    ...
  else
    ...
  endif
enddo

I have used a logical variable "equal" because this is the most general way. But your simple case may be also programmed with less instructions :

Code:
p=0
loop_i : do i=1,n
  do j=1,m
    if(a(i) == b(j)) cycle loop_i
  enddo
  p=p+1
enddo loop_i
 
That's not an easy problem to solve, at least, not efficiently. While this doesn't answer your question directly, you might want to have a look at:
I don't know if it has exactly what you're looking for, but maybe it'll get you part of the way there.

--------------------------------------
Background: Chemical engineer, familiar mostly with MATLAB, but now branching out into real programming.
 
Don't know whether I understood you right, I'd do like this

Code:
PROGRAM Test
IMPLICIT NONE
INTEGER, PARAMETER :: n=6,m=4
INTEGER :: i,j,amount
INTEGER, DIMENSION(n) :: a
INTEGER, DIMENSION(m) :: b
LOGICAL, DIMENSION(m) :: mask
INTEGER, DIMENSION(:), ALLOCATABLE :: aandb

a=RESHAPE((/1,2,3,4,5,6/),(/6/))
b=RESHAPE((/11,12,3,14/),(/4/))
mask(:)=.TRUE.

amount=n+m
DO j=1,m,1
   DO i=1,n,1
      IF(b(j)==a(i))THEN
         amount=amount-1
         mask(j)=.FALSE.
      END IF
   END DO
END DO
ALLOCATE(aandb(amount))
aandb(1:amount-n)=PACK(b,mask)
aandb(amount-n+1:amount)=a


DEALLOCATE(aandb)

END PROGRAM Test

I chose the mask to be the smallest of m and n. I'm quite sure there are more efficient methods without masks, but this is my first try.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top