Question

I am trying to convert cricket overs i.e 6 to show 0.6 and 12 to show 1.6. I got it all working except for the last part where it returns the full figure.

My code:

foreach($numberofballs as $x){
    $first = floor($x / 6);
    $last = $x - ($first * 6);
    echo $first.'.'.$last;
}

Lets assign an array for testing suppose the below array needs to be converted for this loop

$numberofballs = array(1,2,3,4,5,6);

foreach($numberofballs as $x){
    $first = floor($x / 6);
    $last = $x - ($first * 6);
    echo $first.'.'.$last;
}

/* notes
for 1 it does it right = 0.1
for 2 it does it right = 0.2
for 3 it does it right = 0.3
for 4 it does it right = 0.4
for 5 it does it right = 0.5
how its supposed to work for 6:
for 6 I do not want to get = 1 I would like to get 0.6 and no there is never 0.7
/ end notes */

I am not saying the above code is wrong, I am just wishing to get the end value correct.

Was it helpful?

Solution

Try something like this:

foreach( $numberofballs as $x){


       $first = floor($x / 6);
       $last = $x - ($first * 6);
       if($last==0 && $first>0) {$last=6; $first-=1;}
       echo $first.'.'.$last;
    }

OTHER TIPS

Here is an interesting way to handle the problem using base_convert but still handling .6 as the tenth place instead of rolling over after .5:

$numberofballs = range(1,24);

foreach( $numberofballs as $x){

    $round = ceil($x/6) - 1;
    echo  base_convert($x + $round, 10, 7)/10;

}

By using base 7, you retain the .6, but obviously it will be off by 1 for the second group and 2 for the third group, etc. But if we take calculate the round based on the current ball (with the first round being 0, the second 1, etc) and add that to the current ball count before the base convert, it will always be adjusted correctly and still .1 through .6 as the notation.

This avoids the need for a conditional for the adjustment on the 6, 12, 18, etc. as the round calculation adjusts for it regardless of which ball is being calculated. It also can be converted to a simple function to convert any number to the correct notation without needing to track the previous number:

function bowls2overs($ball_number) {

    $round = ceil($ball_number/6) - 1;
    return base_convert($ball_number + $round, 10, 7)/10;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top