I'm trying to find the number of units between 2 numbers that are under zero between 0 and a limit and over that limit. Here is my function. It works fine until I have to work with some huge numbers which takes a lot of time to process. I am trying to find a way to execute this code without using a loop.
public function getBetween($num1, $num2) {
$limit = 500000;
$array = array(0,0,0);
if ($num1 >= $num2) {
$low = $num2;
$high = $num1;
} else {
$low = $num1;
$high = $num2;
}
for($i=$low; $i < $high; $i++) {
if ($i < 0) {
$array[0]++;
} elseif ($i >= 0 && $i < $limit) {
$array[1]++;
} else {
$array[2]++;
}
}
return $array;
}
I have started to split my loop into elseif statements but this is getting messy really quick and I will also have to eventually be able to set more than one limit which will become impossible to use.
if ($low < 0 && $high < 0) {
} elseif ($low < 0 && $high >= 0 && $high < $limit) {
} elseif ($low < 0 && $high >= $limit) {
} elseif ($low >= 0 && $low < $limit && $high < 0) {
} elseif ($low >= 0 && $low < $limit && $high >= 0 && $high < $limit) {
} elseif ($low >= 0 && $low < $limit && $high >= $limit) {
} elseif ($low >= $limit && $high < 0) {
} elseif ($low >= $limit && $high >= 0 && $high < $limit) {
} elseif ($low >= $limit && $high >= $limit) {
}
I am trying to find a clean way to do it. Any ideas?
EDIT
Here is an example of the array I'm trying to get.
If my limit was 500, $num1 = -100 and $num2 = 700 i would get the array
$array[0] = 100
$array[1] = 500
$array[2] = 200
I didn't test it (didn't run a PHP script but I tried it "manually" with a few examples).
You still have loops, but only one iteration per limit (instead of one per unit).
// Example datas
$limits = array(0, 500, 800);
$low = -100;
$high = 1000;
$splittedResults = array();
// Get total of units
$totalUnits = abs($high - $low);
$totalCounted = 0;
foreach($limits as $limit) {
if ($low > $limit) {
// Nothing under the limit
$nbUnderLimit = 0;
} elseif($high < $limit) {
// Both values under the limit
$nbUnderLimit = $totalUnits;
} else {
// $low under the limit and $high over it
$nbUnderLimit = abs($limit - $low);
}
// Here we know how much units are under current limit in total.
// We want to know how much are between previous limit and current limit.
// Assuming that limits are sorted ascending, we have to remove already counted units.
$nbBetweenLimits = $nbUnderLimit - $totalCounted;
$splittedResults[] = $nbBetweenLimits;
$totalCounted += $nbBetweenLimits;
}
// Finally, number of units that are over the last limit (the rest)
$splittedResults[] = $totalUnits - $totalCounted;
You could create an array of the numbers with range() and use array_filter
$count = sizeof(array_filter (range(0,800), function($value){ return ($value > 500); }));
And one for < as well etc.
You only need to define range array once, separately.
Related
Here is the problem, when it encounters fractions like: 300/10 instead of giving a result of "30"
the following code gives me: 1/0
$tokens = explode('/', $value);
while ($tokens[0] % 10 == 0) {
$tokens[0] = $tokens[0] / 10;
$tokens[1] = $tokens[1] / 10;
}
if ($tokens[1] == 1) {
return $tokens[0].' s';
} else {
return '1/'.floor(1/($tokens[0]/$tokens[1])).' s';
// return $tokens[0].'/'.$tokens[1].' s';
}
thanks
You should change the line while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) { to while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) {.
And the line return '1/'.floor(1/($tokens[0]/$tokens[1])).' s'; is not reliable.
If you want to reduce fractions, try this function:
function reduceFraction($fraction) {
sscanf($fraction, '%d/%d %s', $numerator, $denominator, $junk);
// TODO: validation
if( $denominator === null ) {
return (string)$numerator;
}
if( $numerator === $denominator ) {
return 1;
}
$max = max(array($numerator, $denominator));
for($i = 1; $i < $max; ++$i) {
if( $denominator % $i === 0 && $numerator % $i === 0) {
$common = $i;
}
}
if( $denominator === $common ) {
return (string)($numerator / $common);
}
return ($numerator / $common) . '/' . ($denominator / $common);
}
You could use it like this:
reduceFraction('300/10') . ' s';
It's also possible to generalize more the function for chained fractions (eg: '300/100/10'). I can send an implementation of it if you wish.
tell me why the "while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0)"
would be better to use than just "while ($tokens[0] % 100 == 0)" since
both methods seem to work ok
If you try to use the string "3000/10" as an argument for each implementation, the one with while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0) will return 300 s, and the other with while ($tokens[0] % 100 == 0) will return 1/0 s.
If you use the while ($tokens[0] % 100 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 10;
$tokens[0] = 30 / 10 = 30;
$tokens[1] = 10 / 1 = .1;
Stopped because 30 % 100 != 0.
Since the $token[1] is not 1, it does not return "30 s".
1/30 is less than zero (0.0333...), thus floor(1/30) = 0. That's why it returns "1/0 s".
If you use the while ($tokens[0] % 10 == 0 && $tokens[1] % 10 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 1;
Stopped because 1 % 10 != 0.
Since the $token[1] is not 1, it returns "30 s".
It is better because it will work with more inputs.
But I recommend you to use the "reduceFraction" function that I implemented.
It uses the maximum common denominator technique to reduce functions.
echo reduceFraction('3000/10'); outputs "300".
echo reduceFraction('300/10'); outputs "30".
echo reduceFraction('30/10'); outputs "3".
echo reduceFraction('3/10'); outputs "3/10".
echo reduceFraction('3/3'); outputs "1".
echo reduceFraction('222/444'); outputs "1/2".
echo reduceFraction('444/222'); outputs "2".
I am analyzing images and need a fast clustering algorithm which searches for the center of the biggest center.
A sample data set might look like this:
$x = array(6,9,7,0,0,0,4,0,0,6,6,3);
As you see there are 3 clusters in the array.
The result I am looking for is the array position of the center of the cluster with the highest sum.
In the example above this would be 1 as $x[1] is the center of the biggest cluster 6+9+7(=22).
Any ideas?
Whichever way you go, you'll have to walk through the array at least once. The following algorithm does this in one pass without any additional sorting/searching - although I admit that it still may not be the most efficient one. Note that if the biggest cluster has an even number of elements, then it'll return the "lower" mid-point (e.g. for a cluster with indices 0, 1, 2, 3 it will return 1) - this can be easily adjusted in the last line of computation ($mid = ...).
$input = array(6,9,7,0,0,0,4,0,0,6,6,3);
$clust = array(0, 0, 0);
$st = -1;
$sum = 0;
for($i=0; $i<count($input); $i++) {
if($input[$i] == 0) {
if($i == 0) {
continue;
}
elseif($input[$i - 1] == 0) {
continue;
}
else {
if($clust[2] < $sum) {
$clust = array($st, $i - 1, $sum);
}
}
}
else {
if($i == 0 || $input[$i - 1] == 0) {
$st = $i;
$sum = 0;
}
$sum += $input[$i];
}
}
if(end($input) != 0 && $clust[2] < $sum) {
$clust = array($st, $i - 1, $sum);
}
if($clust[2] > 0) {
$mid = (int)(($clust[1] - $clust[0]) / 2);
echo $clust[0] ."->". $mid ."->" . $clust[1] ." = ". $clust[2];
}
else {
echo "No clusters found";
}
The user can only enter a number between 1 and 5 - if they enter 0, leave the field blank or enter a number greater than 5 it will be default reset to 5. 1,2,3,4 are accepted otherwise.
$max=mysql_real_escape_string($_POST["max"]);
if ($max=="0" || $max==""){
$max_r="5";
} elseif ($max > "5"){
$max_r="5";
} else {
$max_r=$max;
}
However it always spits out 5.
Well, you're comparing strings and not integers. Try $max = (int) $_POST['max'] and don't wrap the values in quotes. Then, you can always escape $max before writing it to the DB.
$max = (int) $_POST['max'];
if ( ! $max || $max > 5){
$max_r = 5;
} else {
$max_r = $max;
}
Or, you could go one-liner FTW:
$max_r = ( ! $max || $max > 5) ? 5 : $max;
$max = intval($_POST['max']);
if($max < 0 || $max > 5){
$max = 5;
}
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.
I'm trying to rewrite a pascal program to PHP, and don't understand what this part of pascal function do:
while (u[3] <> 1) and (u[3]<>0) and (v[3]<>0)do
begin
q:=u[3] div v[3];
for i:=1 to 3 do
begin
t:=u[i]-v[i]*q;
u[i]:=v[i];
v[i]:=t;
{writeln('u',i,'=',u[i],' v',i,'=',v[i]); }
end;
end;
if u[1]<0 then u[1]:=n+u[1];
rae:=u[1];
Please help to rewrite it to PHP.
Thanks.
A very literal translation of that code, should be this one:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
{
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
//writeln('u',i,'=',u[i],' v',i,'=',v[i]);
}
}
if ($u[1] < 0 )
$u1] = $n + $u[1];
$rae = $u[1];
Of course, u and v are arrays. Sorry for not giving any more info, but it's been like 10 years since Pascal and I last saw each other, but we had a profound romance for a long time, since I feel inlove for to hotties(C# and PHP) :)
while ($u[3] != 1) && ($u[3] != 0) && ($v[3] != 0) {
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++) {
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo "u$i={$u[$i]} v$i={$v[$i]}\n";
}
}
if ($u[1] < 0) {
$u[1] = $n + $u[1];
}
$rae = $u[1];
2 small corrections to David's code:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
should be
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 0 )
and
for ($i = 1; $i < 3; $i++)
i never reaches the value of 3
for ($i = 1; $i <= 3; $i++)
May be the Writeln can be translated to
echo 'u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
When you do the translation of arrays, take into account that arrays in php uses 0 as the first index.
$u= array( 3, 5, 22 )
echo u[1]; // prints 5
while($u[3] != 1 && $u[3] != 0 && $v[3] != 0)
{
$q = ($u[3] - ($u[3] % $v[3]) ) / $v[3]; //just the same as floor($u[3]/$v[3]), but i want to use % here :)
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i]*$q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo '<br />u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
}
}
if ($u[1] < 0) $u[1] = $n + $u[1];
$rae = $u[1];
I dont know pascal But i have tried :)
while ($u[3]!=1 && $u[3]!=0 && $v[3]!=0) [
$q=floor($u[3]/ $v[3]);
for ($i=1;$i<3;$i++) {
$t=$u[$i]-$v[$i]*$q;
$u[$i]=$v[$i];
$v[$i]=$t;
echo "u".$i."=".$u[$i]."v".$i."=".$v[$i];
}
if ($u[1]<0) {
$u[1]=$n+$u[1];
}
$rae=$u[1];
In php variable Name Start With $
No Begin End used here in php only braces :)