Loading...
Elena123456 avatar Elena123456 235 Точки

04. Star Enigma*(80/100) Regular Expressions - Exercise

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

https://softuni.bg/trainings/resources/officedocument/49595/regular-expressions-exercise-csharp-fundamentals-may-2020/2830

https://judge.softuni.bg/Contests/Compete/Index/1668#3

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

namespace text
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var regexForKey = new Regex(@"[starSTAR]");
            var regexForDecrypt = new Regex(@"[^@!:>-]*@(?<planet>[A-za-z]+)[^@!:>-]*:(?<population>[0-9]+)[^@!:>-]*!(?<attack>[AD])![^@!:>-]*->(?<soldierCount>[0-9]+)[^@!:>-]*");
            var listAttackedPlanets = new List<string>();
            var listDestroyedPlanets = new List<string>();
            int linesNumber = int.Parse(Console.ReadLine());

            for (int i = 0; i < linesNumber; i++)
            {
                string message = Console.ReadLine();
                var matches = regexForKey.Matches(message);
                if (regexForKey.IsMatch(message))
                {
                    int key = matches.Count;
                    string decryptedMessage = string.Empty;
                    foreach (char symbol in message)
                    {
                        int decryptedSymbolInt = symbol - key;
                        char decryptedSymbol = (char)decryptedSymbolInt;
                        decryptedMessage += decryptedSymbol;
                    }

                    var newMatches = regexForDecrypt.Matches(decryptedMessage);
                    if (regexForDecrypt.IsMatch(decryptedMessage))
                    {
                        foreach (Match newmatch in newMatches)
                        {
                            string planet = newmatch.Groups["planet"].Value;
                            string attack = newmatch.Groups["attack"].Value;
                            if (attack == "A")
                            {
                                listAttackedPlanets.Add(planet);
                            }

                            else
                            {
                                listDestroyedPlanets.Add(planet);
                            }
                        }
                    }
                }
            }

            Console.WriteLine($"Attacked planets: {listAttackedPlanets.Count()}");
            foreach (var planet in listAttackedPlanets.OrderBy(x=>x))
            {
                Console.WriteLine($"-> {planet}");
            }

            Console.WriteLine($"Destroyed planets: {listDestroyedPlanets.Count()}");
            foreach (var planet in listDestroyedPlanets.OrderBy(x=>x))
            {
                Console.WriteLine($"-> {planet}");
            }

        }
    }
}

Тагове:
0
C# Fundamentals
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

Regex:

@"@(?<name>[A-Za-z]+)[^@\-!:>]*:(?<population>\d+)[^@\-!:>]*!(?<type>A|D)![^@\-!:>]*->(?<soldierCount>\d+)";

 

;-)

1
Elena123456 avatar Elena123456 235 Точки

Axiomatik, thanks a lot!

With your regex my result in Judge is also 80/100. :(

With my new regex with some corrections in the begining and in the end (@"@(?<planet>[A-za-z]+)[^@!:>-]*:(?<population>[0-9]+)[^@!:>-]*!(?<attack>[A|D])![^@!:>-]*->(?<soldierCount>[0-9]+)") the result is also 80/100.

From my understanding [AD] and [A|D] are doing the same and I don't need "\" to escape the "-", because I placed "-" at the end.

Iam very confused and worried with these regular expressions.

0
22/11/2020 18:45:04
Axiomatik avatar Axiomatik 2422 Точки

The last three exercises (Star Enigma, Nether Realms and Extract Emails) are a bit tricky and I also had difficulties with them. More importantly, start training with the older exams that are available and watch exam preparation videos to see how they are being solved. Unfortunately, C# Advanced won't be easier and you just have to keep up with the new material.

Best,

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

namespace starEnigmaFinal
{
    class Program
    {
        static void Main(string[] args)
        {
            int messages = int.Parse(Console.ReadLine());
            string fullPattern = @"@(?<name>[A-Za-z]+)[^@\-!:>]*:(?<population>\d+)[^@\-!:>]*!(?<type>A|D)![^@\-!:>]*->(?<soldierCount>\d+)";
            string starPattern = @"[starSTAR]";

            List<string> attackedPlanets = new List<string>();
            List<string> destroyedPlanets = new List<string>();

            for (int i = 0; i < messages; i++)
            {
                string message = Console.ReadLine();
                MatchCollection starMatches = Regex.Matches(message, starPattern);
                int countLetters = starMatches.Count;

                string decryptedMessage = string.Empty;

                foreach (var letter in message)
                {
                    decryptedMessage += (char)(letter - countLetters);
                }

                Match planetValid = Regex.Match(decryptedMessage, fullPattern);
                if (planetValid.Success)
                {
                    string planetName = planetValid.Groups["name"].Value;
                    string typeAttack = planetValid.Groups["type"].Value;

                    if (typeAttack == "A")
                    {
                        attackedPlanets.Add(planetName);
                    }
                    else if (typeAttack == "D")
                    {
                        destroyedPlanets.Add(planetName);
                    }
                }
            }

            Console.WriteLine($"Attacked planets: {attackedPlanets.Count}");

            if (attackedPlanets.Any())
            {
                attackedPlanets.Sort();
                foreach (var planet in attackedPlanets)
                {
                    Console.WriteLine($"-> {planet}");
                }
            }

            Console.WriteLine($"Destroyed planets: {destroyedPlanets.Count}");
            if (destroyedPlanets.Any())
            {
                destroyedPlanets.Sort();
                foreach (var planet in destroyedPlanets)
                {
                    Console.WriteLine($"-> {planet}");
                }
            }
        }
    }
}

 

1
22/11/2020 19:11:30
Elena123456 avatar Elena123456 235 Точки

At last... thanks to you I have 100/100. :) https://pastebin.com/NsvW6D7c

1) Judge is serching for  "[A|D]" and it doesn't matter that [AD] and [A|D] are doing the same.

2) Judge dislikes this check up " if (regexForKey.IsMatch(message))
                {
                    int key = matches.Count;
                    string decryptedMessage = string.Empty;
                    foreach (char symbol in message)
                    {
                        int decryptedSymbolInt = symbol - key;
                        char decryptedSymbol = (char)decryptedSymbolInt;
                        decryptedMessage += decryptedSymbol;
                    } "

Should be whitout if condition:

                  var matches = regexForKey.Matches(message);

                    int key = matches.Count;
                    string decryptedMessage = string.Empty;
                    foreach (char symbol in message)
                    {
                        int decryptedSymbolInt = symbol - key;
                        char decryptedSymbol = (char)decryptedSymbolInt;
                        decryptedMessage += decryptedSymbol;

                     }

 

For second if\else condition and the both are valid: "

MatchCollection newMatches = regexForDecrypt.Matches(decryptedMessage); with forech loop", like in my code.

"Match newMatch=regexForDecrypt.Match(decryptedMessage); whitout forech loop", like in your code.

I think your way is better than mine. If I don't need I collection it haven't  reason to used it and to used forech loop for every match. :)

And thanks a lot for your advice. By the way  I plan to spend 6 months with C# Advanced, 2 months with High Quality Code and design patterns : https://softuni.bg/trainings/2706/high-quality-code-december-2019 , 3 months with Data Structure (fundamentals and Advanced) and 3 months with Algorithms (fundamentals and Advanced), before I go to DataBases and Web. After that I will start with HTML, CSS , JavaScript and Agile course... and do my best to not give up.

All the best!

Eli

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