I have a function that gives me a number as result:
Now to make it simple I’ll use an invented example:
function generate($a) {return $a*2;}
//this is just an example, the real generate function is really expensive in terms of speed and resources
I have also an array with the values to pass to that funcion:
$array = array(1,3,4,6,8,9,11);
I’d like to find the value of $array, that, passed to generate(), gives as output the number nearest to 5 and minor of it.
With a progressive search I would get this:
$array[0] => 2;
$array[1] => 6;
$array[2] => 8;
etc.
In this case I’d expect my search function to give as output the number 1 as this is value that, passed into generate(), gives 2 as output, the number nearest and minor to 5.
Since the generate() function is really slow ( 1,5 sec on average ) I want to do a binary search with the hope of reducing the use of my function.
So basically what I want to do is: slice $array into 2 pieces, use generate(), then slice againg etc.
I’m not an expert both in recursive function and binary search (it’s my first script trying to do that).
However I tried to wrote some code I’m pasting below, however it doesn’t work and honestrly I don’t have a clear idea about it.
function generate($a) {return $a*2;}
$array = array(1,2,3,4,5,6,7,8,9);
function find($array) {
$first_half = array_slice($array,0,round(count($array)/2,0));
$second_half = array_slice($array,round(count($array)/2,0));
echo "<pre>";
print_r($first_half);
print_r($second_half);
echo "</pre>";
$last = end($first_half);
$last = generate($last);
if($last > 4) {find($first_half);}
else {}
}
find($array);
Can you help me?
Best regards,
Giorgio
While this may be a good try for some academic research, in practice I think it’s slower than a plain progressive approach.
What you would want is to optimize
generate()(or the way it is called*) rather than the traversal algorithm.*One such improvement is to replace this:
With this: