Last active
August 29, 2015 14:05
-
-
Save birkir/c7729e33803228ad1206 to your computer and use it in GitHub Desktop.
Get most efficient amount of product by volume and price
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function vol_price ($needed) { | |
$table = array( | |
array(250, 0.90), | |
array(330, 1.30), | |
array(500, 2.20), | |
array(1000, 2.50), | |
array(1500, 3.00), | |
array(2000, 4.50) | |
); | |
usort($table, function ($a, $b) { | |
return ($a[1] / $a[0]) > ($b[1] / $b[0]); | |
}); | |
$left = $needed; | |
$res = array(); | |
foreach ($table as $row) | |
{ | |
list($vol, $price) = $row; | |
while ($vol <= $left) | |
{ | |
$res[] = $row; | |
$left -= $vol; | |
} | |
} | |
usort($table, function ($a, $b) { | |
return $a[0] > $b[0]; | |
}); | |
foreach ($table as $ratio => $row) | |
{ | |
list($vol, $price) = $row; | |
if ($vol > $left) | |
{ | |
$res[] = $row; | |
break; | |
} | |
} | |
return $res; | |
} | |
print_r(vol_price(3300)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment