Loading...

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

dxeqtr avatar dxeqtr 0 Точки

Проблем с Predicate Party в Functional Programming

Условието:


Ivancho’s parents are on a vacation for the holidays and he is planning an epic party at home. Unfortunately, his organizational skills are next to non-existent, so you are given the task to help him with the reservations.

On the first line, you receive a list with all the people that are coming. On the next lines, until you get the "Party!" command, you may be asked to double or remove all the people that apply to a given criteria. There are three different criteria:

  • Everyone that has his name starting with a given string
  • Everyone that has a name ending with a given string
  • Everyone that has a name with a given length.

Finally, print all the guests who are going to the party separated by ", " and then add the ending "are going to the party!". If there are no guests going to the party print "Nobody is going to the party!".

Примери: 

1ви:

Pesho Misho Stefan

Remove StartsWith P

Double Length 5

Party!

2ри:

Pesho

Double StartsWith Pesh

Double EndsWith esho

Party!

3ти:

Pesho

Remove StartsWith P

Party!

Примерните тестове минават. Дава ми 60/100 защото някъде имам Runtime Error. Провах няколко кейса, но не намирам къде гърми.

Моля помогнете по моя код:
 

https://pastebin.com/kcVp8Jna


 

 

Тагове:
0
Module: C# Advanced
MartinBG avatar MartinBG 4803 Точки

Гърми при команда Double, когато няма нито едно съвпадение по зададенити критерии, защото липсва такава проверка в кода:

List<string> startsWith = input.Where(x => x.StartsWith(command[2])).ToList(); // startsWith е празен

int index = input.FindIndex(x => x.StartsWith(command[2])); // index = -1

input.InsertRange(index, startsWith); // IndexOutOfRangeException

 

Добавете проверка на индекса преди 3-те input.InsertRange команди и задачата ще мине в Judge:

List<string> startsWith = input.Where(x => x.StartsWith(command[2])).ToList();

int index = input.FindIndex(x => x.StartsWith(command[2]));

if (index != - 1 ) // Валидация на индекса
{
   input.InsertRange(index, startsWith);
}

 

Ето и едно преработено решение от мен:

using System;
using System.Linq;

namespace _10.PredictParty
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var namesList = Console.ReadLine()
                .Split()
                .ToList();

            string command;
            while ((command = Console.ReadLine()) != "Party!")
            {
                var tokens = command.Split().ToList();

                var predicate = GetPredicate(tokens[1], tokens[2]);

                switch (tokens[0])
                {
                    case "Remove":
                        namesList.RemoveAll(predicate);
                        break;
                    case "Double":
                    {
                        var matches = namesList.FindAll(predicate);
                        if (matches.Count > 0)
                        {
                            var index = namesList.FindIndex(predicate);
                            namesList.InsertRange(index, matches);
                        }

                        break;
                    }
                }
            }

            if (namesList.Count != 0)
            {
                Console.WriteLine(string.Join(", ", namesList) + " are going to the party!");
            }
            else
            {
                Console.WriteLine("Nobody is going to the party!");
            }
        }

        private static Predicate<string> GetPredicate(string commandType, string arg)
        {
            switch (commandType)
            {
                case "StartsWith":
                    return (name) => name.StartsWith(arg);
                case "EndsWith":
                    return (name) => name.EndsWith(arg);
                case "Length":
                    return (name) => name.Length == int.Parse(arg);
                default:
                    throw new ArgumentException("Invalid command type: " + commandType);
            }
        }
    }
}

 

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