Loading...

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

Taniaaleksandrova avatar Taniaaleksandrova 6 Точки

3. Post Office - More Exercise - C# Fundamentals

Здравейте,

Имам проблем със задача 3. Post Office - More Exercise , гърмят ми 2 и 9 тест със Runtime error и не мога да разбера къде е проблема, какъвто и вход да въведа работи правилно, но в judge ми дава 80/100.  Ще съм много благодарна, ако някой ми помогне

Ето кода ми - https://pastebin.com/G1cdzTA4

 

Условие

 

You read a single line of ASCII symbols, and the message is somewhere inside it, you must find it.

 The input consists of three parts separated with "|" like this:

"{firstPart}|{secondPart}|{thirdPart}"

Each word starts with capital letter and has a fixed length, you can find those in each different part of the input.

The first part carries the capital letters for each word inside the message. You need to find those capital letters 1 or more from A to Z. The capital letters should be surrounded from the both sides with any of the following symbols – "#, $, %, *, &". And those symbols should match on the both sides. This means that $AOTP$ - is a valid pattern for the capital letters. $AKTP% - is invalid since the symbols do not match.

The second part of the data contains the starting letter ASCII code and words length /between 1 – 20 charactes/, in the following format: "{asciiCode}:{length}". For example, "67:05" – means that '67' - ascii code equal to the capital letter "C", represents a word starting with "C" with following 5 characters: like "Carrot". The ascii code should be a capital letter equal to a letter from the first part. Word's length should be exactly 2 digits. Length less than 10 will always have a padding zero, you don't need to check that.

The third part of the message are words separated by spaces. Those words have to start with Capital letter [A…Z] equal to the ascii code and have exactly the length for each capital letter you have found in the second part. Those words can contain any ASCII symbol without spaces.

When you find valid word, you have to print it on a new line.

Input / Constraints

  • On the first line – the text in form of three different parts separated by "|". There can be any ASCII character inside the input, except '|'.
  • Input will always be valid - you don’t need to check it
  • The input will always have three different parts, that will always be separated by "|".

Output

  • Print all extracted words, each on a new line.
  • Allowed working time / memory: 100ms / 16MB

Examples

Input

Output

Comment

sdsGGasAOTPWEEEdas$AOTP$|a65:1.2s65:03d79:01ds84:02! -80:07++ABs90:1.1|adsaArmyd Gara So La Arm Armyw21 Argo O daOfa Or Ti Sar saTheww The Parahaos

Argo

Or

The

Parahaos

The capital letters are "AOTP"

Then we look for the addition length of the words for each capital letter. For A(65) -> it's 4. For O(79) -> it's 2 For T(84) -> it's 3 For P(80) -> it's 8.

Then we search in the last part for the words.First, start with letter 'A' and we find "Argo". With letter 'O' we find  "Or". With letter 'T' we find "The" and with letter 'P' we find "Parahaos".

Urgent"Message.TO$#POAML#|readData79:05:79:0!2reme80:03--23:11{79:05}tak{65:11ar}!77:!23--)77:05ACCSS76:05ad|Remedy Por Ostream :Istream Post sOffices Office Of Ankh-Morpork MR.LIPWIG Mister Lipwig

 

Post

Office

Ankh-Morpork

Mister

Lipwig

The first capital letters are "POAML"

Then we look for the addition length of the words for each capital letter.

P(80) -> it's 4.

O(79) -> it's 6

A(65) -> it's 12

M(77) -> it's 6

L(76) -> it's 6.

Then we search the last part for the words. First, start with the letter 'P' and we find "Post". With letter 'O' we find "Office". With letter 'A' we find "Ankh-Morpork". With letter 'M' we find "Mister" and with letter 'L' we find "Lipwig".

Тагове:
0
Fundamentals Module
Elena123456 avatar Elena123456 235 Точки

Здравейте, тествах  вашето решение и поне на мен ми изглежда, че няма проблем. Това, което аз установих е, че Judge не харесва втория речник с числата от втората част. За това го махнах и просто разделих мачваните елементи от втората част на  групи, като първата група е съответно инт числото на първата буква от думата, а втората група ще е инт дължината на думата.

Видях, че в кода има два мачвания на буквите от първата част- Match на буквите и MatchCollection на вече мачнатите букви. Разбирам, защо сте сложили два пъти едни и същи мачвания, защото и аз се измъчих с възможността да взема всяка отделна буква за да мога после да ги foreach(). От това, което тествах съм на мнение, че и този подход Judge недолюбва. За това махнах вторият MatchCollection на буквите и просто превърнах първия Match на буквите в стринг, като взех само групата  "capitalLetters". Така вече ще имаме възможността да вземем всяка отделна буква, като чар и да foreach() по-нататъка.

И като се има предвид всичко това, заради Judge направих всяко едно конвертиране от инт в чар или от стринг, през инт в чар  и пр. на отделен ред.

100/100

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;


namespace PostOffice
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] symbols = Console.ReadLine().Split('|').ToArray();

            string firstPattern = @"(\$|#|%|\*|&)(?<capitalLetters>[A-Z]+)(\1)";
            string secondPattern = @"([0-9][0-9]):([0-9][0-9])";
            Match matchLetters = Regex.Match(symbols[0], firstPattern);
            string allLetters = matchLetters.Groups["capitalLetters"].Value;
            MatchCollection matchesNumbers = Regex.Matches(symbols[1], secondPattern);  

        
            var letters = new Dictionary<char, int>();
            foreach (char letter in allLetters)
            {
                foreach (Match digits in matchesNumbers)
                {
                    string firstDigit = digits.Groups[1].Value;
                    int firstLetterInt = int.Parse(firstDigit);
                    char firstLetterChar = (char)firstLetterInt;
                    string wordLength = digits.Groups[2].Value;
                    int wordLengthInt = int.Parse(wordLength);

                    if (letter == firstLetterChar && letters.ContainsKey(letter)==false)
                    {
                        letters[letter] = wordLengthInt + 1;
                        break;
                    }
                }
            }

 

            string[] words = symbols[2].Split(' ').ToArray();

            foreach (var kvp in letters)
            {
                char letter = kvp.Key;
                int wordLength = kvp.Value;

                foreach (string word in words)
                {
                    char currentFirstLetter = word[0];
                    int currentWordLength = word.Length;

                    if (letter == currentFirstLetter && wordLength == currentWordLength)
                    {
                        Console.WriteLine(word);
                        break;
                    }

                }
            }
        }
    }
}

 

 

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