I'm working on some PHP code but I'm stuck with a logic. I need to find out the number of squares from a rectangle.
I'm unable to implement this in PHP.
Please help.
I tried this:
function getcount($length,$breadth,$count=0){
$min=min($length,$breadth);
if($length>$breadth){
$length=$length-$min;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$min;
$count++;
return getcount($length,$breadth,$count);
}
else{
$count+=($length/$min);
}
return $count;
}
But some how it doesn't pass all the use cases. And i do not know on which use cases, it fails?
For example: If the rectangle is of size 6×9. We can cut it into 54 squares of size 1×1, 0 of size 2×2, 6 of size 3×3, 0 of size 4×4, 0 of size 5×5 and 0 of size 6×6.
a 3x4 grid has 12 1x1 (3 * 4) squares 6 2x2 (2 * 3) squares and 2 3x3 squares = 20.
I think the easiest way to calculate the number of squares in a rectangle is to substract the found squares from it while it disappears completely.
It works fine for me:
function getcount($width,$height) {
$total=0;
while($width && $height)
{
if($width>$height)
{
$width-=$height;
}
else if($height>$width)
{
$height-=$width;
}
else
{
$width=0;
$height=0;
}
$total+=1;
}
return $total;
}
echo getcount(5,3)."<br/>";
echo getcount(5,5)."<br/>";
echo getcount(11,5)."<br/>";
Output:
4
1
7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With