Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Gandalfcho12 avatar Gandalfcho12 2 Точки

02. Shopping List

Input

You will receive an initial list with groceries separated by an exclamation mark "!".

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. Otherwise, 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. Otherwise, skip this command.

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

Input

Output

Tomatoes!Potatoes!Bread

Unnecessary Milk

Urgent Tomatoes

Go Shopping!

Tomatoes, Potatoes, Bread

Input

Output

Milk!Pepper!Salt!Water!Banana

Urgent Salt

Unnecessary Grapes

Correct Pepper Onion

Rearrange Grapes

Correct Tomatoes Potatoes

Go Shopping!

Milk, Onion, Salt, Water, Banana

 

using System;
using System.Linq;

namespace _02._Shopping_List
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] products = Console.ReadLine()
                .Split("!", StringSplitOptions.RemoveEmptyEntries)
                .ToArray();

            string input = string.Empty;
            string[] urgentArray;
            string[] unessesaryArray;
            string[] saveArray=products;
            string[] rearrangeArray;
            int count = 0;
            while ((input=Console.ReadLine())!= "Go Shopping!")
            {
                string[] inputArray = input
                    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                    .ToArray();

                string command = inputArray[0];
                if (command== "Urgent")
                {
                    string item = inputArray[1];
                    if (products.Contains(item))
                    {
                        continue;
                    }
                    count++;
                    urgentArray = new string[products.Length+count];
                    urgentArray[0] = item;
                    for (int i = 1; i < urgentArray.Length; i++)
                    {
                        if (i<products.Length)
                        {
                            urgentArray[i] = products[i - 1];
                        } 
                    }
                    saveArray = urgentArray;
                }
                else if (command== "Unnecessary")
                {
                    string item = inputArray[1];
                    unessesaryArray = new string[products.Length - 1];
                    if (saveArray.Contains(item))
                    { int j = 0;
                        for (int i = 0; i < saveArray.Length; i++)
                        {
                            if (saveArray[i]!=item)
                            {
                                unessesaryArray[j] = saveArray[i];
                                j++;
                            }
                        }
                        saveArray = unessesaryArray;
                    }
                    continue;
                }
                else if (command== "Correct")
                {
                    string oldName = inputArray[1];
                    string newName = inputArray[2];
                    if (saveArray.Contains(oldName))
                    {
                        for (int i = 0; i < saveArray.Length; i++)
                        {
                            if (saveArray[i]==oldName)
                            {
                                saveArray[i] = newName;
                            }
                        }
                    }
                    continue;
                }
                else if (command== "Rearrange")
                {
                    string item = inputArray[1];
                    rearrangeArray = saveArray;
                    if (saveArray.Contains(item))
                    {
                        for (int i = 0; i < saveArray.Length; i++)
                        {
                            if (saveArray[i]==item && i+1<rearrangeArray.Length)
                            {
                                rearrangeArray[i] = saveArray[i + 1];
                            }
                            else
                            {
                                rearrangeArray[i] = saveArray[i];
                                
                            }
                            rearrangeArray[rearrangeArray.Length - 1] = item;
                        }
                        saveArray = rearrangeArray;
                    }
                    continue;
                }
            }
            Console.WriteLine(string.Join(", ",saveArray));
        }
    }
}

Ако накой разбере начина ми на решение добре ако не може да покажете свое решение на задачата.Условието е ,че искам задачата да се реши със МАСИВ а не със ЛИСТ с лист ще е елементарно.Ако някой я е решавал с МАСИВИ моля да сподели Благодаря.

 

Линк към ДЖЪДЖ -https://judge.softuni.org/Contests/Practice/Index/2031#1

Тагове:
1
C# Fundamentals 04/02/2023 15:45:19
MartinBG avatar MartinBG 4803 Точки

Избягвайте да дефинирате променливи извън скоупа, в който са необходими.

100/100:

using System;
using System.Linq;

namespace _02._Shopping_List
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] products = Console.ReadLine()
                .Split("!", StringSplitOptions.RemoveEmptyEntries)
                .ToArray();

            string input;
            while ((input = Console.ReadLine()) != "Go Shopping!")
            {
                string[] inputArray = input
                    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                    .ToArray();

                string command = inputArray[0];
                if (command == "Urgent")
                {
                    string item = inputArray[1];
                    if (products.Contains(item))
                    {
                        continue;
                    }

                    string[] updatedProducts = new string[products.Length + 1];
                    updatedProducts[0] = item;
                    for (int i = 0; i < products.Length; i++)
                    {
                        updatedProducts[i + 1] = products[i];
                    }

                    products = updatedProducts;
                }
                else if (command == "Unnecessary")
                {
                    string item = inputArray[1];
                    if (!products.Contains(item))
                    {
                        continue;
                    }

                    string[] updatedProducts = new string[products.Length - 1];
                    for (int i = 0, j = 0; i < products.Length; i++)
                    {
                        if (products[i] != item)
                        {
                            updatedProducts[j++] = products[i];
                        }
                    }

                    products = updatedProducts;
                }
                else if (command == "Correct")
                {
                    string oldName = inputArray[1];
                    string newName = inputArray[2];

                    for (int i = 0; i < products.Length; i++)
                    {
                        if (products[i] == oldName)
                        {
                            products[i] = newName;
                        }
                    }
                }
                else if (command == "Rearrange")
                {
                    string item = inputArray[1];

                    for (int i = 0; i < products.Length - 1; i++)
                    {
                        if (products[i] == item)
                        {
                            products[i] = products[i + 1];
                            products[i + 1] = item;
                        }
                    }
                }
            }

            Console.WriteLine(string.Join(", ", products));
        }
    }
}

 

1
Gandalfcho12 avatar Gandalfcho12 2 Точки

Благодаря!

1
IrennaStoyneva avatar IrennaStoyneva 3 Точки
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class P02ShoppingList {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        List<String> itemsList = Arrays.stream(scanner.nextLine().split("!")).collect(Collectors.toList());

        String commands = scanner.nextLine();
        while (!commands.equals("Go Shopping!")){
           String commList = commands.split(" ")[0];

            switch (commList){
                case "Urgent":
                    String com = commands.split(" ")[1];
                    if (!itemsList.contains(com)){
                        itemsList.add(0, com);
                    }
                    break;
                case "Unnecessary":
                    String itemRemove = commands.split(" ")[1];
                    if (itemsList.contains(itemRemove)){
                        itemsList.remove(itemRemove);
                    }
                    break;
                case "Correct":
                    String oldItem = commands.split(" ")[1];
                    String newItem = commands.split(" ")[2];
                    if (itemsList.contains(oldItem)){
                        itemsList.set(1, newItem);
                    }
                    break;
                case "Rearrange":
                    String addRemoveItem = commands.split(" ")[1];
                    if (itemsList.contains(addRemoveItem)){
                        itemsList.remove(addRemoveItem);
                        itemsList.add(addRemoveItem);
                    }

                    break;

            }
            commands = scanner.nextLine();
        }
        System.out.println(String.join(", ", itemsList));
    }
}

 

Това е моят код на задачата, в Intellij всичко е както трябва, но judje ми дава 60/100. Виждате ли къде може да греша ?

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.