Extremes in Direction

JOR, 5Feb10

Given a set of points (or a polygon), find the extreme points in a given direction.

Input: P, and direction vector u, not assumed to be unit.

MakeUnitVec[v_]:=N[v/Sqrt[v.v]];

Extreme[P_,v_]:=Module[{i,n,u,dot,max=-∞,min=∞,imin,imax},
u=MakeUnitVec[v];
n=Length[P];
For[i=1,i≤n,i++,
dot= u.P[[i]];
If[dot<min,min=dot;imin=i];
If[dot>max,max=dot;imax=i];
];(*For*)
If[debug,Print["Extreme:{imin,min}=",{imin,min}," {imax,max}=",{imax,max}]];
Return[{imin,imax}]
];

Test[P_,v_]:=Module[{imin,imax},
{imin,imax}=Extreme[P,v];
g=Graphics[{
{Red,PointSize[0.02],Point[P[[imin]]],Point[P[[imax]]]},
{Blue,PointSize[0.01],Map[Point[#]&,P]},
{Green,Thick,Line[{{0,0},v}]}
},
Axes->True,AspectRatio->Automatic
];
Print[g]
];

P=Table[{RandomReal[],RandomReal[]},{28}]

Test[P,{4,2}]