我有多个产品,都有大小,我需要找到最便宜的配置,满足最低要求的大小。
例如,约翰需要至少10升的存储空间——可以多一些,但不能少一些。
有2L、3L、5L、8L和10L可选(但这可能会改变)。
作为一个例子,它可能更便宜得到:
1x10L容器或
2x5L容器或
1x2L、1x3L和1x5L或
4x3L(这个已经超过10L了,但还是有可能会便宜些)
到目前为止,我已经尝试过多次循环(因为通常最大要求是40升),但在某些情况下,我的内存用完了,这似乎不是最有效的方法。
// Size is in mL
$available_containers = [
[
'id' => 22700,
'price' => 1190,
'size' => 2000,
],
[
'id' => 22701,
'price' => 1245,
'size' => 3000,
],
[
'id' => 22702,
'price' => 1415,
'size' => 4000,
],
[
'id' => 22715,
'price' => 12300,
'size' => 5000,
],
[
'id' => 22706,
'price' => 1740,
'size' => 5000,
],
[
'id' => 22703,
'price' => 1510,
'size' => 5000,
],
[
'id' => 22707,
'price' => 1790,
'size' => 6000,
],
[
'id' => 22704,
'price' => 1770,
'size' => 6000,
],
[
'id' => 22708,
'price' => 2215,
'size' => 7000,
],
[
'id' => 22705,
'price' => 2195,
'size' => 8200,
],
[
'id' => 22709,
'price' => 2660,
'size' => 8200,
],
[
'id' => 22710,
'price' => 2799,
'size' => 10000,
],
[
'id' => 22711,
'price' => 2910,
'size' => 12500,
],
[
'id' => 22712,
'price' => 3260,
'size' => 15000,
],
[
'id' => 22713,
'price' => 4130,
'size' => 20000,
],
[
'id' => 22714,
'price' => 3770,
'size' => 27000,
]
];
$required_size = 8; // Can change.
$container_install = 5;
foreach ( $available_containers as $v ){
foreach ( $available_containers as $v2 ){
foreach ($available_containers as $v3 ) {
foreach ( $available_containers as $v4 ){
$all_configs = [
[
'size' => $v['size'],
'configuration' => [ $v['size'] ],
'price' => $v['price'],
],
[
'size' => $v['size'] + $v2['size'],
'configuration' => [ $v['size'], $v2['size'] ],
'price' => $v['price'] + $v2['price'] + $container_install,
],
[
'size' => $v['size'] + $v2['size'] + $v3['size'],
'configuration' => [ $v['size'], $v2['size'], $v3['size'] ],
'price' => $v['price'] + $v2['price'] + $v3['price'] + $container_install + $container_install,
],
[
'size' => $v['size'] + $v2['size'] + $v3['size'] + $v4['size'],
'configuration' => [ $v['size'], $v2['size'], $v3['size'], $v4['size'] ],
'price' => $v['price'] + $v2['price'] + $v3['price'] + $v4['price'] + $container_install + $container_install + $container_install,
],
];
foreach ( $all_configs as $c ){
if ( $c['size'] >= $required_size ){
$configuration[] = array(
'configuration' => $c['configuration'],
'size' => $c['size'],
'price' => $c['price'],
);
}
}
}
}
}
}
// Sort by price.
$sorted_configs = array_sort($configuration, 'price', SORT_ASC); // This function simply sorts all permutations by price
最佳答案
好吧,有一些点可以使这些环重量轻这个问题必须用分而治之的方法来解决。
创建一个子阵列,因为你不需要整个阵列,一个新的子阵列从1L到10L只有。
子数组应按价格从低到高顺序排序。
当且仅当第一个指数所代表的最低价格只能购买一次时,break
循环。
否则,您应该有一个列表,在您已经循环时获取输出。
关于php - PHP找到最便宜的排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55034585/