[英]showing all possible options with a budget for food items in php
現在我有一個代碼,它顯示了 3 種食物的所有可能結果,唯一的事情是我希望它用我給 readline 提供的預算來做它需要顯示這樣的東西
• 6 個最壞的、100 個漢堡包、75 個 frikandellen
• 6 個最壞的、160 個漢堡包、25 個 frikandellen
• 12 個最壞的、30 個漢堡包、100 個 frikandellen
每件商品的價格
• 最差(6 包)5 歐元
• 漢堡包(20 包)10 歐元
• Frikandellen(25 包)15 歐元
我的PHP代碼
<?php
function f_($n) {
if($n<2) { return 1; }
for($x = 2;$n-1>1;$x*=$n--);
return $x;
}
function array_restore($r) {
$clean = array();
if(is_array($r)) {
foreach($r as $k) {
$clean[] = $k;
}
}
return $clean;
}
function connect($arr){
$back = "";
foreach($arr as $a){
if($back != ""){
$back .= " ";
}
$back .= $a;
}
return $back;
}
function cmb($v) {
$str = count($v);
$tot = f_($str);
$combo = array();
for($i=0;$i<$tot*8;$i++) {
shuffle($v);
$sf = connect($v);
if(!in_array($sf, $combo)){
$combo[] = $sf;
}
}
$x = array_unique($combo);
return array_restore($x);
}
var_dump(cmb(array("frikandel"=>15 , "worst"=>5, "hamburger"=>10)));
function pc_permute($items, $perms = array( )) {
$back = array();
if (empty($items)) {
$back[] = join(' ', $perms);
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$back = array_merge($back, pc_permute($newitems, $newperms));
}
}
return $back;
}
現在我得到這個作為我的輸出 現在我得到這個
[0]=>
string(7) "15 5 10"
[1]=>
string(7) "5 10 15"
[2]=>
string(7) "15 10 5"
[3]=>
string(7) "10 5 15"
[4]=>
string(7) "10 15 5"
[5]=>
string(7) "5 15 10"
相反,我需要得到這樣的東西
• 6 個最壞的、100 個漢堡包、75 個 frikandellen
• 6 個最壞的、160 個漢堡包、25 個 frikandellen
• 12 個最壞的、30 個漢堡包、100 個 frikandellen
這就是我為解決您的問題而提出的(我很抱歉,但它與您的代碼沒有任何共同之處)。
<?php
$budget = 200;
//The idea is, to iterate over each food combination, until the budget is cracked.
//The loop stops, after the last food item exceeds the limit all by itself.
$counts = [ 0, 0, 0 ];
while (true)
{
$total =
$counts[0] * 5 //Worst
+ $counts[1] * 10 //Hamburger
+ $counts[2] * 15; //Frikandellen
if ($total < $budget - 5) //Still room left for one more in the budget.
++$counts[0];
else if (!$counts[0]) //The total was exceeded with the current combination without adding a single worst.
{
if (!$counts[1]) //The final iteration has been reached.
break;
else
{
++$counts[2];
$counts[1] = 0;
}
}
else
{
echo sprintf("%d worsten, %d hamburgers, %d frikandellen\n",
$counts[0] * 6,
$counts[1] * 20,
$counts[2] * 25
);
++$counts[1]; //Increment the next place.
$counts[0] = 0; //And reset the previous iteration.
}
}
?>
這是對該主題的一種相當蠻力的方法,並且有相當多的優化潛力,但它應該為您指明正確的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.