随机商品*数量接近目标最低价

今天接到一个网单,编写一个算法,传入一个商品数组,获取5个商品,每个商品的数量随机,商品*数量=设定目标接近价,目前想到的办法只有递归。
代码如下:
protected function execute()
{
    $products = [];
    for ($i = 1; $i <= 100; $i++) {
        $products[] = [
            "id" => $i,
            "name" => "商品" . $i,
            "price" => rand(1, 100),
        ];
    }
    $result = self::get_random_order($products, 1000);
    print_r($result);

}

public static function get_random_order($products, $order_amount)
{
    //随机5个商品
    $selected_indices = array_rand($products, 5);
    $selected_products = array_intersect_key($products, array_flip($selected_indices));
    $min_product_price = min(array_column($selected_products, 'price'));

    //随机商品数量
    $quantities = [];
    foreach ($selected_products as $product_index => $product) {
        $quantities[$product_index] = rand(1, intval($order_amount / $product["price"])); // 随机选择商品数量
    }

    // 计算总价
    $total_price = array_reduce(array_keys($selected_products), function ($carry, $product_index) use ($selected_products, $quantities) {
        // 使用商品的索引作为键来访问 $quantities 数组
        return $carry + $selected_products[$product_index]["price"] * $quantities[$product_index];
    }, 0);

    // 加入商品数量
    foreach ($selected_products as $product_index => $product) {
        $selected_products[$product_index]["quantity"] = $quantities[$product_index];
    }

    if (abs($total_price - $order_amount) < $min_product_price) { // 如果总价与订单金额相近,则返回结果
        return ["products" => $selected_products, "total_price" => $total_price, "min_product_price" => $min_product_price];
    } else {
        return self::get_random_order($products, $order_amount); // 重新生成订单
    }
}

 

 
posted @ 2024-03-21 23:32  北漂生活  阅读(6)  评论(0编辑  收藏  举报