Forum Moderators: coopster & phranque

Message Too Old, No Replies

How do I find a minimum?

         

k8tie

9:55 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



I have a function which finds distances between locations. [ It produces $distance ]

I want to create a function that checks these distances to find the minimum one out of all of them => ie it checks the second distance to the first distance and if it is smaller than it, the smaller one is recorded etc. Then finally I print out the smallest distance found.

Can anyone help me please? :)
Thanks

ikbenhet1

10:04 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



You could put the $distance in an array like this:

$data[$no]=$distance;
$no=$no+1;

and then use

sort($data);

and the lowest value should now be in $data[0]

there is probably much simpeler code,but my php knowledge is limited.

k8tie

11:00 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



Thanks
I had already thought of this but am trying to minimise computational overhead? Does anyone have a neater way to do this?

ikbenhet1

11:08 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



I just figured out,

$data[$no]=$distance;
$no=$no+1;

can be replace with

$data .=$distance;

and don't use sort($data) in the loop but outside it, but you probably already figured that out.

<added>Anybodt that know better ways please post them, and if i'm mistaking please do report</added>

k8tie

11:43 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



erm, I don't getcha?

ikbenhet1

11:51 pm on Mar 2, 2003 (gmt 0)

10+ Year Member



>> erm, I don't getcha?

I tried to explain(my fault i guess, bad english? i'm dutch) that you should use the sort command after you have put all the variables in $data.(i wrote 'loop', sorry for that)

And not use sort everytime you add a value to $data. Because that would be a overhead, because then you sort the same array many times.

stevedob

12:09 pm on Mar 3, 2003 (gmt 0)

10+ Year Member



Your question actually contains the answer. Keep track of a local minimum, and compare against it each time you calculate a new distance. If the comparison produces a smaller value, make that your new minimum for subsequent comparisons.