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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to find the highest value in a subset of one column of a two-column array....and more 1

Status
Not open for further replies.

FiascoBurnett

Programmer
May 25, 2015
6
0
0
ZA
Hi
I’ve been struggling with this problem for a while, and perhaps somebody can help.
I have a 2-column array, e.g. as follows
3 2
6 4
12 0
- - - -
22 3
23 10
. .
. .
. .
66 4
I need to search column 1 (which is in ascending order) until I find a specified number, e.g. 12, then find the maximum value in column 2 up to that point, i.e. 4. I then need to find the number in the first column corresponding to this, i.e. 6. Then continue down the array until we see 4 again in the second column and return the corresponding number in the first column, i.e. 66.
There must be a concise and elegant way to do this, perhaps using intrinsic functions.
 
I am afraid that a programming language can't simply provide intrinsic functions for everybody's wishes and desires...that's why one writes programs.

Code:
[pre]
program max_location
    integer :: i, j, k, num
    integer, dimension(1)    :: max_loc
    integer, dimension(15,2) :: m
    ! example data
    m(:,1) = (/ 3, 6,12,15,17,21,22,23,26,28,33,44,53,66,71/)
    m(:,2) = (/ 2, 4, 0, 3,10,12, 6, 8, 5,14, 1, 7,11, 4 ,3/)
    num = 12
    ! algorithm
    i = 1
    do j = 1, 2
        do while ( m(i,j) /= num )
            i = i + 1
        end do
        if ( j == 2 ) exit
        max_loc = maxloc(m(1:i,2))
        k = max_loc(1)
        num = m(k, 2)
        i = k + 1
    end do
    write(*,*) ' first  number = ', m(k,1)
    write(*,*) ' second number = ', m(i,1)
end program max_location
[/pre]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top