Re: Maximum in a list
- To: mathgroup at smc.vnet.net
 - Subject: [mg97240] Re: [mg97209] Maximum in a list
 - From: DrMajorBob <btreat1 at austin.rr.com>
 - Date: Mon, 9 Mar 2009 01:03:31 -0500 (EST)
 - References: <200903081050.FAA21521@smc.vnet.net>
 - Reply-to: drmajorbob at bigfoot.com
 
Here's a simple method:
mylist = {{1, 2}, {3, 4}, {8, 3}};
select[s_List] := s[[Ordering[s[[All, 2]], -1]]]
mylist = RandomInteger[{1, 4}, {50, 2}]
select@mylist
{{3, 3}, {1, 2}, {4, 1}, {1, 3}, {4, 3}, {1, 4}, {1, 2}, {1, 4}, {1,
   3}, {3, 4}, {4, 2}, {3, 1}, {2, 1}, {3, 3}, {3, 4}, {4, 2}, {4,
   4}, {2, 1}, {4, 2}, {4, 3}, {1, 3}, {3, 2}, {2, 2}, {4, 2}, {2,
   4}, {1, 4}, {4, 1}, {4, 3}, {3, 1}, {3, 1}, {3, 4}, {2, 1}, {3,
   3}, {4, 1}, {3, 1}, {4, 3}, {3, 4}, {4, 4}, {2, 1}, {4, 3}, {3,
   1}, {4, 2}, {1, 1}, {3, 2}, {1, 2}, {2, 1}, {4, 1}, {1, 2}, {3,
   3}, {1, 4}}
{{1, 4}}
"select" returns the LAST element for which the second element is maximum,  
which may not be what you want. If you want the FIRST such element, change  
"select" to
Clear[select]
select[s_List] := s[[Ordering[Reverse@s[[All, 2]], -1]]]
select@mylist
{{1, 2}}
For either of those, you could add First@ to get only the element, rather  
than a list with only that element:
Clear[select]
select[s_List] := First@s[[Ordering[Reverse@s[[All, 2]], -1]]]
select@mylist
{1, 2}
If you want ALL pairs for which the second element is maximum, then:
Clear[select]
select[s_List] := Extract[s, Position[s[[All, 2]], Max@s[[All, 2]]]]
select@mylist
{{1, 4}, {1, 4}, {3, 4}, {3, 4}, {4, 4}, {2, 4}, {1, 4}, {3, 4}, {3,
   4}, {4, 4}, {1, 4}}
If you want the same thing without repeats, you can do it with:
Clear[select]
select[s_List] :=
  Union@Extract[s, Position[s[[All, 2]], Max@s[[All, 2]]]]
select@mylist
{{1, 4}, {2, 4}, {3, 4}, {4, 4}}
or
Clear[select, unsortedUnion]
unsortedUnion[s_List] := Tally[s][[All, 1]]
select[s_List] :=
  unsortedUnion@Extract[s, Position[s[[All, 2]], Max@s[[All, 2]]]]
select@mylist
{{1, 4}, {3, 4}, {4, 4}, {2, 4}}
or
Clear[select]
select[s_List] :=
  DeleteDuplicates@Extract[s, Position[s[[All, 2]], Max@s[[All, 2]]]]
select@mylist
{{1, 4}, {3, 4}, {4, 4}, {2, 4}}
Bobby
On Sun, 08 Mar 2009 05:50:59 -0500, pacotomi <pacotomi at orange.fr> wrote:
> Hi,
>  Suppose a list
>
> mylist={{1,2},{3,4},{8,3}}
>
> I would like to extract the element {i,j} of mylist for which j is max
> (here, it is the second one {3,4}).
>
> Somebody could help me, please?
>
> Pacotomi
>
>
>
>
-- 
DrMajorBob at bigfoot.com
- References:
- Maximum in a list
- From: pacotomi@orange.fr (pacotomi)
 
 
 - Maximum in a list