<?php
$rules = [
'1' => '1.2',
'5-10' => '6.25',
'10-15' => '9.2',
'15-20' => '10.9',
];
function costFromWeight($weight, array $newRules): array {
$parsed = [];
foreach ($newRules as $range => $cost) {
if (sscanf($range, '%d-%d', $min, $max) === 1) {
$default = [$min, $min, (float) $cost];
} else {
$parsed[] = [$min, $max, (float) $cost];
}
}
$result = ['cost' => 0];
while ($weight > 0) {
foreach ($parsed as $i => [$min, $max, $cost]) {
if ($weight <= $max) {
if (!$i && $weight <= $min) {
[$min, $max, $cost] = $default;
}
break;
}
}
$result[$max] = ($result[$max] ?? 0) + 1;
$result['cost'] += $cost;
$weight -= $max;
}
return $result;
}
foreach ([49, 47.75, 38, 35, 23, 15, 14, 10.5, 4] as $weight) {
echo "$weight :: ";
print_r(costFromWeight($weight, $rules));
echo "\n---\n";
}
preferences:
39.88 ms | 405 KiB | 5 Q