现在,我有一个代码,显示了所有可能的结果与3个食品项目,唯一的事情是,我希望它做的预算,我给出的重新行,它需要显示这样的东西
*6份工作,100份汉堡包,75份薯条
*6名工作人员,160名汉堡包,25名薯条
* 12份工作,30份汉堡包,100份薯条
每项价格
·最差(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份薯条
*6名工作人员,160名汉堡包,25名薯条
* 12份工作,30份汉堡包,100份薯条
发布于 2022-06-24 09:51:10
这就是我想出的解决问题的方法(我很抱歉,但它与您的代码没有任何共同之处)。
<?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.
}
}
?>这是一个相当蛮力的方法,并有相当多的优化潜力,但它应该指向正确的方向。
https://stackoverflow.com/questions/72741580
复制相似问题