directory
directory

Reputation: 3167

Calculate how many times a static number fits into another number

For a surface calculation I am searching for the following solution.

I have a size of the surface like 60m², for this square I have 2 kind of materials sizes. Material size of 2m² and 4m². The challenge for me now is to calculate the needed materials efficiently as possible and keep a rest of the material to the minimum.

So, filling a surface of 60m² with most as possible with 4m² materials and fill it up with 2m2 to keep material to the minimum.

Upvotes: 1

Views: 1163

Answers (2)

talsibony
talsibony

Reputation: 8756

assuming you are using PHP This will be a start to find the material with minimum rest.

function getMinRest($surface, $num1, $num2){
  $rest1 = $surface % $num1;
  $rest2 = $surface % $num2;
  return $rest2 <= $rest1 ? $num2:$num1;
}

Upvotes: 1

vaso123
vaso123

Reputation: 12391

It's simple. With this method, you can use any number and any size of materials.

Store your materials into an array. Loop through on that array, make the calculations, and store the "rest" in another variable. If at the end there will be some rest, then add 1 more from the last item.

$materials = array(2,4,8);
$surface = 63;
rsort($materials);
$rest = $surface;
$isFinished = false;
$data = array();
foreach ($materials as $material) {
    $result = $rest / $material;
    if ($result >= 1) {
        $data[$material] = floor($result);
        $rest -= $material * floor($result);
    }
}

if ($rest > 0) {
    $data[end($materials)]++;
}
echo "For a " . $surface . " you need the following materials: <br />";
foreach ($data as $key => $val) {
    echo "Material " . $key . " * " . $val ."<br />";
}

Output is:

For a 63 you need the following materials:
Material 8 * 7
Material 4 * 1
Material 2 * 2

Upvotes: 2

Related Questions