tags:

views:

187

answers:

3
1st number:  50
2.           30
3.           70
4.           40
5.           11

and other number is 33

I need to calculate which two numbers the last number is between (using php) .. any help?

+2  A: 

Hey,

I'll not give you the code but give you some guidelines for your homework.

You need to do these steps to solve your problem.

  • Sort your list of numbers. (I guess you are storing them in an array so sort the array.)
  • With a for loop search for the place where the element N is bigger than your number and the element N-1 is smaller. That will give you your position.
  • Oh and to avoid really long loop. use "break" after you find your position.

Sorted List:

11
30
 // your 33 is bigger than 30 and smaller than 40, so this is the position you want.
40
50
70
fmsf
+5  A: 

Iterate over your list and find the following two values:

  • The largest number that is smaller than your target number.
  • The smallest number that is larger than your target number.

In pseudo-code:

lowerlimit = Unknown
upperlimit = Unknown
for each n in list:
    if (n <= target) and (lowerlimit is Unknown or n > lowerlimit):
        lowerlimit = n
    if (n >= target) and (upperlimit is Unknown or n < upperlimit):
        upperlimit = n

Then lowerlimit and upperlimit are your answer. This algorithm requires O(n) time and O(1) extra space.

If you are going to test the same list with many different target numbers then it could make sense to sort the list first requiring O(n log(n)) time, but then you can find the limits in just O(log(n)) time using a binary search.

Mark Byers
A: 

function isBetween($several_numbers, $number)
{
   $return_numbers = array();
   sort($several_numbers);
   $j = 0;
   //find the first number in the array that $number is bigger than
   while($number > $several_numbers[$j])  $j++;
   if ($j == 0 || $j > count($several_numbers) - 1) return array();
   $return_numbers[0] = $several_numbers[$j-1];
   while($number > $several_numbers[$j]) $j++;
   if ($j > count($several_numbers)-1) return array();
   $return_numbers[1] = $several_numbers[$j];
   return $return_numbers;
}
print_r(isBetween(array(50, 30, 70, 40, 10), 33));

I don't know if I understood correctly but this seems to be it

matei