Re: Algorithm help for unique string searching/counting within an array.




Paul Van Delst schreef:



As *** Hendrickson pointed out in his post, once the array is sorted, the uniqueness
determination is pretty trivial. I find the above pretty easy to understand. It sure is a
*lot* tidier than the dog's dinner of a program I originally posted! :o)


Here is a solution without sorting the arrays:

program count_unique
! Define some sensor strings
character(len=30), dimension(24) :: cArray

cArray = (/ 'abi_gr ','imgr_g13
','windsat_coriolis',&
'amsua_metop-c ','amsub_n15 ','amsua_n18
',&
'amsua_n18 ','hirs3_n17 ','hirs3_n15
',&
'modis_terra ','mhs_metop-a ','amsua_metop-b
',&
'amsua_metop-c ','amsub_n15 ','amsua_n18
',&
'amsua_n18 ','hirs3_n17 ','hirs3_n15
',&
'modis_terra ','mhs_metop-a ','amsua_metop-b
',&
'abi_gr ','imgr_g13
','windsat_coriolis'/)

call count_unique_strings( cArray, number )
write(*,*) 'Number = ', number

contains
subroutine count_unique_strings( cArray, number )
character(len=*), dimension(:) :: cArray
integer :: number

character(len=len(cArray)), dimension(size(cArray)) :: cunique
integer :: i

number = 0
do i = 1,size(cArray)
if ( all(cunique(1:number) .ne. cArray(i) ) ) then
number = number + 1
cunique(number) = cArray(i)
endif
enddo
end subroutine
end program

If you use an index array, then you do not need to copy the strings
into a separate
array (saving memory). It may be slower than first sorting, being
O(N**2) instead
of O(N ln N).

Regards,

Arjen

.


Quantcast