I’m still a beginner in php and need some help from you with my coding. I need to calculate how many layers i can make with the available blocks.
see example below. For example, if i have 6 blocks, the pyramide will be 3 layers high, with 10 blocks 4 layers high ect. See example below
Thank you in advance.
<?php
$blocks = readline("Enter how many blocks are available for a pyramid?") . PHP_EOL;
$h = 1;
while ($h <= $blocks) {
$layers = $h++;
}
echo $layers;
Is there any solution for this?
2
Answers
This might be an approach:
The strategy: you decrement the number of blocks required for the next lower layer in each iteration. If the resulting number of blocks is smaller than zero (there were not enough blocks for that layer), then skip and output the layers so far. Otherwise count that full layer and start over again.
@NigelRen pointed out another approach in his comment below. I had to adjust it slightly, but it leads to a much more compact solution:
That would be a corresponding unit test class:
So, the no. of blocks per layer increases consecutively like,
You have been given the no. of blocks and you wish to find out the layers. This is like the sum of
n
consecutive numbers wheren
is no. of the layers andsum
is the total blocks available.The math formula is ,
In our case, we are given the sum and we need to find the value of
n
that is a nearest match to the sum when substituted in the above formula. We can simplify the equation as:So our code would look like,
Online Demo
For an efficient approach, you can rewrite the equation as:
Using the
quadratic formula
, we can directly get the value ofn
as below,Online Demo