首页 热点专区 义务教育 高等教育 出国留学 考研考公

请问这个用php怎么写

发布网友

我来回答

1个回答

热心网友

$list = [
    [
        'id' => 'a',
        'weight' => 2,
        'money' => 6
    ],
    [
        'id' => 'b',
        'weight' => 2,
        'money' => 3
    ],
    [
        'id' => 'c',
        'weight' => 6,
        'money' => 5
    ],
    [
        'id' => 'd',
        'weight' => 5,
        'money' => 4
    ],
    [
        'id' => 'e',
        'weight' => 4,
        'money' => 6
    ]
];

$pack = 10;

$result = [];

$max = ['money' => 0];

foreach ($list as $item) {
    $process = [
        'count' => $item['weight'],
        'money' => $item['money'],
        'list' => [$item]
    ];
    foreach ($list as $_item) {
        if ($_item !== $item) {
            if ($process['count'] + $_item['weight'] <= $pack) {
                $process['count'] += $_item['weight'];
                $process['money'] += $_item['money'];
                $process['list'][] = $_item;
            }
        }
        if ($process['count'] === $pack) break;
    }
    $result[] = $process;
    if ($max['money'] < $process['money']) $max = $process;
}

//全部组合
print_r($result);

//价值最大组合
print_r($max);

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com