settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Shopping List - PHP Exam Task

+4 votes

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:

shopping list php exam task

asked in PHP category by user andrew

1 Answer

+4 votes

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);
answered by user mitko
...