Loading...

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

jerrynp avatar jerrynp 4 Точки

02. Mirror Words - 03. Programming Fundamentals Final Exam Retake - 88/100

02. Mirror Words

On the first line of the input, you will be given a text string. To win the competition, you have to find all hidden word pairs, read them, and mark the ones that are mirror images of each other.

First of all, you have to extract the hidden word pairs. Hidden word pairs are:

  • Surrounded by "@" or "#" (only one of the two) in the following pattern #wordOne##wordTwo# or @wordOne@@wordTwo@
  • At least 3 characters long each (without the surrounding symbols)
  • Made up of letters only

If the second word, spelled backward, is the same as the first word and vice versa (casing matters!), they are a match, and you have to store them somewhere. Examples of mirror words:

#Part##traP# @leveL@@Level@ #sAw##wAs#

  • If you don`t find any valid pairs, print: "No word pairs found!"
  • If you find valid pairs print their count: "{valid pairs count} word pairs found!"
  • If there are no mirror words, print: "No mirror words!"
  • If there are mirror words print:

"The mirror words are:

{wordOne} <=> {wordtwo}, {wordOne} <=> {wordtwo}, … {wordOne} <=> {wordtwo}"

Input / Constraints

  • You will recive a string.

Output

  • Print the proper output messages in the proper cases as described in the problem description.
  • If there are pairs of mirror words, print them in the end, each pair separated by ", ".
  • Each pair of mirror word must be printed with " <=> " between the words.

Examples

Input

@mix#tix3dj#poOl##loOp#wl@@bong&song%4very$long@thong#Part##traP##@@leveL@@Level@##car#rac##tu@pack@@ckap@#rr#sAw##wAs#r#@w1r 

Output

Comments

5 word pairs found!

The mirror words are:

Part <=> traP, leveL <=> Level, sAw <=> wAs

There are 5 green and yellow pairs that meet all requirements and thus are valid.

#poOl##loOp# is valid and looks very much like a mirror words pair, but it isn`t because the casings don`t match.

#car#rac# "rac" spelled backward is "car", but this is not a valid pair because there is only one "#" between the words.

@pack@@ckap@ is also valid, but "ckap" backward is "pakc" which is not the same as "pack", so they are not mirror words.

 

Здравейте! Прегледах си кода и условието на задачата многократно, но не мога да видя къде ми е грешката... дава ми 88/100, като гърми на Test #7 . Всякакви входни данни пробвах да подам, работи нормално. Явно ще е някое изключение, за което не се сещам...
Това ми е кодът - https://pastebin.com/KTxNQ8D1

Тагове:
0
C# Fundamentals
tt104 avatar tt104 15 Точки

не мога да видя къде ми е грешката

Няма изискване думите в двойката да са с еднаква дължина.
Проиграйте си кода с "@fff@@fffn@". Резултата не е ок.

Имате поне една грешка при "firstPart" и "secondPart"; още: тяхното присъствие в кода е грешка само по себе си - то не е необходимо; пробвайте (класа пада, "тонове" код изчезват): 

foreach (Match match in wordPairs)
{
    var ms = match.ToString ();
    if (ms.IsPalindrome ())
        mirrorWords.Add (ms.Trim (new char[] { '#', '@' }).Replace ("##", " <=> ").Replace ("@@", " <=> "));
}

Регулярен израз който намира двойките (можете да го ползвате за еталон при тестване):

grep -o '\([@#]\)[A-z]\{3,\}\1\1[A-z]\{3,\}\1'

Втората част от условието касае палиндром. Пробвайте:

internal static bool IsPalindrome(this string value)
{
    if (string.IsNullOrEmpty (value)) return false; // Empty string policy
    for (int i = 0, j = value.Length - 1; i < value.Length / 2; i++, j--)
        if (value[i] != value[j]) return false;
    return true;
}

Когато wordPairs.Count <= 0, какъв точно е смисъла да проверявате за палиндроми?
В момента за вход "fsdfsdlk" програмата Ви ще отпечата:
"No word pairs found!"
"No mirror words!"
А дали трябва?

Вашия код с малко мои кръпки + мое решение + автоматизиран тест от 100000 различни входни стринга:

internal static class MyStringExtensions
{
    /// <summary>When the string is null or empty returns false; otherwise returns true when the string is a palindrome</summary>
    internal static bool IsPalindrome(this string value)
    {
        if (string.IsNullOrEmpty (value)) return false; // Empty string policy
        for (int i = 0, j = value.Length - 1; i < value.Length / 2; i++, j--)
            if (value[i] != value[j]) return false;
        return true;
    }
}

class Program
{
    // Generates random input; use "expected" to compare the output of your Analyze()
    static string Gen(ref List<string> expected)
    {
        // generate random string of random length filled with the allowed symbols
        const string SYM = "#@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rnd = new Random ();
        StringBuilder s = new StringBuilder (rnd.Next (104));
        for (int i = 0; i < s.Capacity; i++) s.Append (SYM[rnd.Next (SYM.Length)]);

        // put random number of pairs and palindromes in it
        StringBuilder palidromes = new StringBuilder ();
        int pairs = rnd.Next (5), actual_pairs = 0, pos = 0;
        for (int i = 0; i < pairs; i++)
        {
            int rnd_ofs = rnd.Next (5);
            // gen the pair
            int rnd_w1_len = 3 + rnd.Next (5);
            int rnd_w2_len = 3 + rnd.Next (5);
            StringBuilder words_builder = new StringBuilder (rnd_w1_len + rnd_w2_len);
            for (int j = 0; j < words_builder.Capacity; j++) words_builder.Append (SYM[2 + rnd.Next (SYM.Length - 2)]);
            var words = words_builder.ToString ();
            var word1 = words.Substring (0, rnd_w1_len);
            var word2 = words.Substring (rnd_w1_len, rnd_w2_len);
            bool palindrome = 0 == rnd.Next (5) % 2;
            char rnd_sep = SYM[rnd.Next (2)];
            string pair = string.Format ("{0}{1}{0}{0}{2}{0}", rnd_sep, word1,
                (palindrome ? new string (word1.Reverse ().ToArray ()) : word2));
            // is there space left
            pos += rnd_ofs;
            if (pos + pair.Length > s.Length) break;
            //
            if (palindrome) palidromes.Append (FormatPalindrome (pair) + ", ");
            actual_pairs++; s.Remove (pos, pair.Length); s.Insert (pos, pair); pos += pair.Length;
        }
        if (0 == actual_pairs) expected.Add ("No word pairs found!");
        else
        {
            expected.Add (string.Format ("{0} word pairs found!", actual_pairs));
            if (palidromes.Length <= 0) expected.Add ("No mirror words!");
            else
            {
                expected.Add ("The mirror words are:");
                Debug.Assert (palidromes.Length > 3 + 3 + 4, "Bug: min pair length is 10");
                palidromes.Remove (palidromes.Length - 2, 2);
                expected.Add (palidromes.ToString ());
            }
        }
        return s.ToString ();
    }

    static string FormatPalindrome(string value)
    {
        return value.Trim (new char[] { '#', '@' }).Replace ("##", " <=> ").Replace ("@@", " <=> ");
    }

    // Your solution patched as described.
    static List<string> Analyze_YourCodeWithMyPatchesEdition(string input)
    {
        List<string> result = new List<string> ();

        const string pattern = @"(?<separate>[@#]{1})[A-Za-z]{3,}\k<separate>{2}[A-Za-z]{3,}\k<separate>";
        List<string> mirrorWords = new List<string> ();
        MatchCollection wordPairs = Regex.Matches (input, pattern);
        foreach (Match match in wordPairs)
        {
            var ms = match.ToString ();
            if (ms.IsPalindrome ())
                mirrorWords.Add (ms.Trim (new char[] { '#', '@' }).Replace ("##", " <=> ").Replace ("@@", " <=> "));
        }
        if (wordPairs.Count > 0)
        {
            result.Add (string.Format ("{0} word pairs found!", wordPairs.Count));
            if (mirrorWords.Count > 0)
            {
                result.Add ("The mirror words are:");
                result.Add (string.Join (", ", mirrorWords));
            }
            else
                result.Add ("No mirror words!");
        }
        else
            result.Add ("No word pairs found!");
        return result;
    }

    // My solution
    static List<string> Analyze(string input)
    {
        List<string> result = new List<string> ();

        const string pattern = @"(?<separate>[@#])[A-z]{3,}\k<separate>{2}[A-z]{3,}\k<separate>";
        if (string.IsNullOrEmpty (input)) throw new Exception ("Wrong input");
        var wordPairs = Regex.Matches (input, pattern);
        if (wordPairs.Count <= 0)
            result.Add ("No word pairs found!");
        else
        {
            result.Add (string.Format ("{0} word pairs found!", wordPairs.Count));
            var palindromes = wordPairs.Cast<Match> ().Select (m => m.ToString ()).Where (w => w.IsPalindrome ()).ToArray ();
            if (palindromes.Length <= 0) result.Add ("No mirror words!");
            else
            {
                result.Add ("The mirror words are:");
                StringBuilder p = new StringBuilder ();
                p.Append (FormatPalindrome (palindromes[0]));
                for (int i = 1; i < palindromes.Length; i++)
                    p.Append (", " + FormatPalindrome (palindromes[i]));
                result.Add (p.ToString ());
            }
        }

        return result;
    }

    static void Main()
    {
#if TEST
        // Automated test
        Stopwatch sw = new Stopwatch ();
        sw.Start ();
        List<string> expected = new List<string> ();
        const int TEST_ITERATIONS = 100000;
        for (int t = 0; t < TEST_ITERATIONS; t++)
        {
            expected.Clear ();
            Console.Write (string.Format ("Test {0}/{1}\r", t + 1, TEST_ITERATIONS));
            var input = Gen (ref expected);
            var actual = Analyze_YourCodeWithMyPatchesEdition (input);
            //var actual = Analyze (input);
            for (int i = 0; i < expected.Count; i++)
                if (i >= actual.Count || actual[i] != expected[i])
                {
                    Console.WriteLine ("Bug:");
                    Console.WriteLine ("Input:\"" + input + "\"");
                    Console.WriteLine ("Expected:"); foreach (var l in expected) Console.WriteLine (l);
                    Console.WriteLine ("Actual:"); foreach (var l in actual) Console.WriteLine (l);
                    break;
                }
        }
        sw.Stop ();
        Console.WriteLine ();
        Console.WriteLine ("Time: " + sw.ElapsedMilliseconds + " ms");
#endif
        foreach (var l in Analyze_YourCodeWithMyPatchesEdition (Console.ReadLine ())) Console.WriteLine (l);
        Console.ReadLine ();
    }
}// class Program

 

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