Home>

I wrote a program for the following problem, but I would like to know that this is better for variable names and flow.
Thank you.

/**

  • Product A
  • Made of 2 parts A and 1 part B.
  • Product B
  • It consists of 3 parts C and 2 parts D.
  • Product C
  • Consists of 1 part B and 1 part D.
  • Order product A, product B, and product C one by one at random.
  • Parts are in stock and manufactured until they run out.
  • Finally output the following:
  • Number of parts in stock before production
  • Product orders
  • Number of manufactured products
  • Number of parts in stock after production
    */
$part_names = [
    'part1' =>'A',
    'part2' =>'B',
    'part3' =>'C',
    'part4' =>'D',
];
$part_stocks = [
    'part1' =>120,
    'part2' =>120,
    'part3' =>130,
    'part4' =>130,
];
$product_names = [
    'product1' =>'A',
    'product2' =>'B',
    'product3' =>'C',
];
$needed_parts_counts = [
    'product1' =>[
        'part1' =>2,
        'part2' =>1,
    ],
    'product2' =>[
        'part3' =>3,
        'part4' =>2,
    ],
    'product3' =>[
        'part2' =>1,
        'part4' =>1,
    ],
];
$first_part_stocks = $part_stocks;
$product_counts = [];
$order_count = 0;
while (true) {
    $makeable_product_ids = [];
    foreach ($needed_parts_counts as $product_id =>$needed_parts_count) {
        $can_make = true;
        foreach ($needed_parts_count as $part_id =>$needed_part_count) {
            if ($part_stocks [$part_id]>$needed_part_count) {
                $can_make = false;
                break;
            }
        }
        if ($can_make) {
            $makeable_product_ids [] = $product_id;
        }
    }
    if (count ($makeable_product_ids) === 0) {
        break;
    }
    $ordered_product_id = $makeable_product_ids [array_rand ($makeable_product_ids)];
    $order_count ++;
    if (isset ($product_counts [$ordered_product_id])) {
        $product_counts [$ordered_product_id] ++;
    } else {
        $product_counts [$ordered_product_id] = 1;
    }
    foreach ($needed_parts_counts [$ordered_product_id] as $part_id =>$needed_part_count) {
        $part_stocks [$part_id]-= $needed_part_count;
    }
}
echo "Before production<br>";
foreach ($first_part_stocks as $part_id =>$part_stock) {
    echo 'parts'. $part_names [$part_id]. ''. $part_stock. "pcs<br>";
}
echo "<br>";
echo 'order'. $order_count. 'times<br>';
foreach ($product_counts as $product_id =>$product_count) {
    echo 'Products'. $product_names [$product_id]. ''. $product_count. "pcs<br>";
}
echo "<br>";
echo "After production<br>";
foreach ($part_stocks as $part_id =>$part_stock) {
    echo 'parts'. $part_names [$part_id]. ''. $part_stock. "pcs<br>";
}
php