Open
Description
To list the unique elements of a 1D array, one can sort the array and then find the positions of new elements. This is a common task -- should it be added to stdlib with a name such as new_loc? Here is an implementation for an array of integers.
module m_mod
implicit none
contains
pure function new_loc(vec) result(ipos)
! return the positions of the new elements in vec(:), including the first element
integer, intent(in) :: vec(:)
integer, allocatable :: ipos(:)
integer :: i,inew,n,nnew
n = size(vec)
if (n == 0) then
allocate (ipos(0))
return
else if (n == 1) then
ipos = [1]
return
end if
nnew = count(vec(2:) /= vec(:n-1)) + 1
allocate (ipos(nnew))
ipos(1) = 1
inew = 1
do i=2,n
if (vec(i) /= vec(i-1)) then
inew = inew + 1
ipos(inew) = i
end if
end do
end function new_loc
end module m_mod
!
program xnew_loc
use m_mod, only: new_loc
print*,new_loc([3])
print*,new_loc([3,3,1,1,2])
print*,new_loc([integer ::]) ! test on zero-sized array
print*,"done"
end program xnew_loc
gives output
1
1 3 5
done