4
19/10/2024 10:07 f m
Ämnesstart
It’s the end of the week and it is time for you to go shopping, so you need to create a shopping list first.
Input:
You will receive an initial list with groceries separated by "!".
After that you will be receiving 4 types of commands, until you receive "Go Shopping!"
- Urgent {item} - add the item at the start of the list. If the item already exists, skip this command.
- Unnecessary {item} - remove the item with the given name, only if it exists in the list. Otherwise skip this command.
- Correct {oldItem} {newItem} – if the item with the given old name exists, change its name with the new one. If it doesn't exist, skip this command.
- Rearrange {item} - if the grocery exists in the list, remove it from its current position and add it at the end of the list.
Constraints:
- There won`t be any duplicate items in the initial list
Output:
Print the list with all the groceries, joined by ", ".
- "{firstGrocery}, {secondGrocery}, …{nthGrocery}"
Examples:
1 Answer
3
19/10/2024 10:08 f m
Here is my solution to this task:
<?php $arr = explode("!", readline()); $input = readline(); while ($input != "Go Shopping!") { $args = explode(" ", $input); $command = $args[0]; switch ($command) { case 'Urgent': $item = $args[1]; if (!in_array($item, $arr)) { array_unshift($arr, $item); } break; case 'Unnecessary': $item = $args[1]; if (in_array($item, $arr)) { $index1 = array_search($item, $arr); array_splice($arr, $index1, 1); } break; case 'Correct': $item = $args[1]; if (in_array($item, $arr)) { $index1 = array_search($item, $arr); array_splice($arr, $index1, 1, $args[2]); } break; case 'Rearrange': $item = $args[1]; if (in_array($item, $arr)) { $index1 = array_search($item, $arr); array_splice($arr, $index1, 1); array_push($arr, $item); } } $input = readline(); } echo implode(", ", $arr);
Vänligen Logga in eller Registrera dig för att svara på detta ämne.