Confusing Math Problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jack_indigo
Forum Contributor
Posts: 186
Joined: Sun Jun 08, 2008 11:25 pm

Confusing Math Problem

Post by jack_indigo »

You have a summary gadget on a web page. Its goal is not to show the whole set of results, just some of those results. One then clicks View All and see the rest. So, there are 3 variables:

$a - # of active accounts in the system
$e - # of expired accounts in the system
$T - # specified in a conf file on how many items to show in the summary gadget

Each of these are known and you pass it to a function like:

function DisplaySummary($a, $e, $T)

The goal is to show as many active accounts as you can and as many expired accounts as you can, but no more than the value of $T for both of them together. So, in general, var $a should not be > ceil($T/2). But if var $a <= ceil($T/2), then give preference to var $e. You also have to take into account rounding, so if $T is 9, which does not divide evenly, then give preference to either var $a or var $e, whichever is >= ceil($T/2).

So, I'm trying to figure out the if/then logic.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Confusing Math Problem

Post by VladSun »

You have too many undefined cases:
- $a = $e > $T/2
- $a > $T and $e > $T

and I don't see how $T/2 is important:

Code: Select all

function calc($a, $e, $T)
{
    if ($a > $T || $e > $T)
        return null; // unspecified
        
    if ($a = $e && $a > $T /2)
        return null; // unspecified
        
    if ($a + $e <= $T)
        return array($a, $e);
 
    if ($a > $e)
        return array($a, $T - $a);
    else 
        return array($T - $e, $e);
}
There are 10 types of people in this world, those who understand binary and those who don't
jack_indigo
Forum Contributor
Posts: 186
Joined: Sun Jun 08, 2008 11:25 pm

Re: Confusing Math Problem

Post by jack_indigo »

This is what I settled on:

Code: Select all

$H = ceil($T/2);
 
if (($a >= $H) and ($e >= $H)) {
    $sa = $H;
    $se = $T - $H;
} else if (($a >= $H) and ($e < $H)) {
    $se = $e;
    $sa = $T - $e;
} else if (($a < $H) and ($e >= $H)) {
    $sa = $a;
    $se = $T - $a;
} else if (($a < $H) and ($e < $H)) {
    $sa = $a;
    $se = $T - $a;
} else {
    $sa = $H;
    $se = $T - $H;
}
The output is $sa and $se. I don't even know if the last else is even necessary, but it's a failsafe.
Post Reply