3
19/10/2024 3:01 am
Topic starter
Write a program to calculate the total cost of different types of furniture. You will be given some lines of input until you receive the line "Purchase".
For the line to be valid it should be in the following format:
">>{furniture name}<<{price}!{quantity}"
The price can be floating point number or whole number. Store the names of the furniture and the total price. At the end print the each bought furniture on separate line in the format:
"Bought furniture:
{1st name}
{2nd name}
…"
And on the last line print the following:
"Total money spend: {spend money}" formatted to the second decimal point.
Examples:
1 Answer
2
19/10/2024 3:02 am
Here is my solution:
<?php $input = readline(); $pattern = '/>>([A-Za-z]+)<<([\d]+[\d.]{1,})!(\d+)/'; $matches = []; $totalMoneySpent = 0; echo "Bought furniture:" . PHP_EOL; while ($input !== "Purchase") { if (preg_match($pattern, $input, $matches)) { $product = $matches[1]; $price = $matches[2]; $quantity = $matches[3]; $totalMoneySpent += $price * $quantity; echo $product . PHP_EOL; } $input = readline(); } $totalMoneySpent = number_format($totalMoneySpent, 2, ".", ""); echo "Total money spend: " . $totalMoneySpent;
You should know the difference between preg_match and preg_match_all functions in PHP:
- preg_match stops looking after the first match.
- preg_match_all, on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.