Beispiel #1
0
        public static void PigLatin(string input)
        {
            string[] arr    = input.Split();
            char[]   vowels = new char[5] {
                'a', 'e', 'i', 'o', 'u'
            };
            string conv = "";

            foreach (string item in arr)
            {
                if (vowels.Any(c => c.Equals(item[0])))
                {
                    conv += item;
                }
                if (!vowels.Any(c => c.Equals(item[0])))
                {
                    for (int i = 1; i < item.Length; i++)
                    {
                        conv += item[i];
                    }
                    conv += item[0];
                }
                conv += "ay ";
            }
            Console.WriteLine(conv);
        }
Beispiel #2
0
        public static bool IsPalindrome(string input)
        {
            input = input.ToLower();
            int forward  = 0;
            int backward = input.Length - 1;

            char[] characterToIgnore = new char[] { ' ', '.', '\'', '-', ',', '!', ':', '?' };

            while (backward > forward && (backward - forward) > 1)
            {
                char currentLeft  = input[forward];
                char currentRight = input[backward];

                if (characterToIgnore.Any(x => x == currentLeft))
                {
                    forward++;
                    continue;
                }
                if (characterToIgnore.Any(x => x == currentRight))
                {
                    backward--;
                    continue;
                }
                if (currentLeft == currentRight)
                {
                    forward++;
                    backward--;
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #3
0
        // Password must be at least 8 characters
        // -------- must contain at least one uppercase letter, lowercase letter and digit
        public static Boolean IsValidPassword(SecureString password)
        {
            if (password == null)
            {
                return(false);
            }
            if (password.Length < 8)
            {
                return(false);
            }
            Boolean hasLowercaseLetter = false;
            Boolean hasUppercaseLetter = false;
            Boolean hasDigit           = false;

            Char[] chars = new char[password.Length];
            IntPtr ptr   = IntPtr.Zero;

            try
            {
                ptr = Marshal.SecureStringToGlobalAllocUnicode(password);
                Marshal.Copy(ptr, chars, 0, password.Length);
                hasLowercaseLetter = chars.Any(Char.IsLower);
                hasUppercaseLetter = chars.Any(Char.IsUpper);
                hasDigit           = chars.Any(Char.IsDigit);
            }
            finally
            {
                Array.Clear(chars, 0, chars.Length);
                Marshal.ZeroFreeGlobalAllocUnicode(ptr);
            }

            return(hasLowercaseLetter && hasUppercaseLetter && hasDigit);
        }
Beispiel #4
0
        public static void Main()
        {
            int rows = int.Parse(Console.ReadLine());

            char[][] matrix           = new char[rows][];
            int[]    positionOfFirst  = new int[2];
            int[]    positionOfSecond = new int[2];

            for (int row = 0; row < rows; row++)
            {
                matrix[row] = Console.ReadLine().ToCharArray();
                for (int col = 0; col < matrix[row].Length; col++)
                {
                    if (matrix[row][col] == 'f')
                    {
                        positionOfFirst = new int[] { row, col };
                    }
                    else if (matrix[row][col] == 's')
                    {
                        positionOfSecond = new int[] { row, col };
                    }
                }
            }

            bool firstIsAlive  = true;
            bool secondIsAlive = true;

            while (firstIsAlive && secondIsAlive)
            {
                string[] commandsArgs = Console.ReadLine().Split();

                string directionForFirst  = commandsArgs[0];
                string directionForSecond = commandsArgs[1];

                positionOfFirst = Move(matrix, directionForFirst, positionOfFirst, "first");

                if (matrix.Any(x => x.Any(y => y == 'x')))
                {
                    break;
                }

                positionOfSecond = Move(matrix, directionForSecond, positionOfSecond, "second");

                if (matrix.Any(x => x.Any(y => y == 'x')))
                {
                    break;
                }
            }

            foreach (var row in matrix)
            {
                Console.WriteLine(String.Join("", row));
            }
        }
        public void TestAny()
        {
            var    array          = new char[] { 'b', 'd', 'x', 'y' };
            bool   isBetweenAAndC = array.Any(c => c > 'a' && c < 'c');
            bool   isGreaterThanZ = array.Any(c => c > 'z');
            string exceptionArray = null;

            Assert.True(isBetweenAAndC);
            Assert.False(isGreaterThanZ);

            var exception = Assert.Throws <ArgumentNullException>(() => exceptionArray.Any(c => c > 'a'));

            Assert.Equal("source", exception.Message);
        }
Beispiel #6
0
        public override object GetFirstAnwer(string input)
        {
            int wordCount = 0;

            char[]        vovels     = new char[] { 'a', 'e', 'i', 'o', 'u' };
            List <string> badLetters = new List <string>()
            {
                "ab", "cd", "pq", "xy"
            };

            foreach (var line in input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
            {
                if (!badLetters.Any(s => line.Contains(s)))
                {
                    if (line.Count(s => vovels.Any(ss => ss == s)) >= 3)
                    {
                        int longestRun = line.Select((c, i) => line.Substring(i).TakeWhile(x => x == c).Count()).Max();
                        if (longestRun > 1)
                        {
                            wordCount++;
                        }
                    }
                }
            }
            return(wordCount);
        }
Beispiel #7
0
        internal void Solve()
        {
            var password = new char[8];

            using (MD5 md5 = MD5.Create())
            {
                int i = 0;
                while (password.Any(x => x == 0))
                {
                    var hash = MD5Hash(md5, input + i);
                    if (hash.StartsWith("00000"))
                    {
                        var location = hash[5] - '0';
                        if (location >= 0 && location <= 7 && password[location] == 0)
                        {
                            password[location] = hash[6];
                        }
                    }

                    i++;
                }
            }

            Console.WriteLine($"Password is: {new string(password).ToLower()}");
        }
Beispiel #8
0
        public static string RemoveBracket(this string str, char chr, string[] exept = null)
        {
            if (str.Contains(chr))
            {
                string tmp = str;

                char[] special = new char[] { '[', '{' };

                for (int i = 0; i < str.Count(c => c == chr); ++i)
                {
                    if (exept != null && exept.Any(e => tmp.GetBracketContent(chr, 0).StartsWith(e)))
                    {
                        continue;
                    }
                    int start  = tmp.IndexOfNth(chr, 0);
                    int offset = 1;

                    if (special.Any(s => chr.Equals(s)))
                    {
                        offset = 2;
                    }
                    int end = tmp.IndexOfNth((char)((int)chr + offset), 0);
                    tmp = tmp.Remove(start, end - start + 1);
                }

                return(tmp);
            }
            else
            {
                return(str);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Get the name of the collection based off the model. Will appropriatly pluralize
        /// </summary>
        /// <typeparam name="TModel">The type of the model to use</typeparam>
        /// <returns>The name of the collection</returns>
        protected static string GetCollectionName <TModel>()
        {
            Type   modelType       = typeof(TModel);
            string modelName       = modelType.Name;
            string collectionName  = string.Empty;
            char   endingCharacter = modelName[modelName.Length - 1];

            //Be smart about English
            if (char.ToLowerInvariant(endingCharacter) == 'y')
            {
                char   nextChar = modelName[modelName.Length - 2];
                char[] vowels   = new char[] { 'a', 'e', 'i', 'o', 'u' };
                if (vowels.Any(v => v == nextChar))
                {
                    collectionName = string.Concat(modelName, 's'); //bays, toys, keys
                }
                else
                {
                    collectionName = string.Concat(modelName.Substring(0, modelName.Length - 2), "ies"); //histories, flies, countries, etc.
                }
            }
            else if (char.ToLowerInvariant(endingCharacter) == 'o') //Gonna have the odd case here...pianoes
            {
                collectionName = string.Concat(modelName, "es");
            }
            else
            {
                collectionName = string.Concat(modelName, 's'); //Bows, Arrows
            }
            return(collectionName);
        }
Beispiel #10
0
        private void CopyToolStripMenuItemClick(object sender, EventArgs e)
        {
            string code = _internalFileViewer.GetSelectedText();

            if (string.IsNullOrEmpty(code))
            {
                return;
            }

            if (_currentViewIsPatch)
            {
                //add artificail space if selected text is not starting from line begining, it will be removed later
                int    pos      = _internalFileViewer.GetSelectionPosition();
                string fileText = _internalFileViewer.GetText();
                int    hpos     = fileText.IndexOf("\n@@");
                //if header is selected then don't remove diff extra chars
                if (hpos <= pos)
                {
                    if (pos > 0)
                    {
                        if (fileText[pos - 1] != '\n')
                        {
                            code = " " + code;
                        }
                    }

                    string[] lines    = code.Split('\n');
                    char[]   specials = new char[] { ' ', '-', '+' };
                    lines.Transform(s => s.Length > 0 && specials.Any(c => c == s[0]) ? s.Substring(1) : s);
                    code = string.Join("\n", lines);
                }
            }

            Clipboard.SetText(code);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            char[] vowels = new char[] { 'E', 'e', 'U', 'u', 'I', 'i', 'O', 'o', 'A', 'a' };

            int[] results = new int[n];

            for (int i = 0; i < n; i++)
            {
                int    sum  = 0;
                string name = Console.ReadLine();

                for (int j = 0; j < name.Length; j++)
                {
                    char currIndex = name[j];

                    if (vowels.Any(x => x == name[j]))
                    {
                        sum += currIndex * name.Length;
                    }
                    else
                    {
                        sum += currIndex / name.Length;
                    }
                }
                results[i] = sum;
            }

            Console.WriteLine(string.Join(Environment.NewLine, results.OrderBy(x => x)));
        }
Beispiel #12
0
        private static string CrackCode2(string input)
        {
            char[] code = new char[8];

            ulong index = 0;

            while (code.Any(x => x == 0))
            {
                string hash = CreateMD5(input + index);
                if (hash.StartsWith("00000") && hash[5] >= '0' && hash[5] <= '7')
                {
                    int  position = hash[5] - '0';
                    char c        = hash[6];

                    if (code[position] == 0)
                    {
                        code[position] = c;
                    }
                }

                ++index;
            }

            return(new string(code));
        }
Beispiel #13
0
        private static void SolvePart2()
        {
            var key      = File.ReadAllText("Input.txt");
            var password = new char[8];
            var i        = 0;

            using (var md5 = MD5.Create())
            {
                while (password.Any(c => c == '\0'))
                {
                    var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(key + i.ToString()));
                    var hex  = BitConverter.ToString(hash).Replace("-", "");
                    if (hex.Substring(0, 5) == "00000" && char.IsDigit(hex[5]))
                    {
                        var pos = int.Parse(hex[5].ToString());
                        if (pos < 8 && password[pos] == '\0')
                        {
                            password[pos] = hex[6];
                        }
                    }

                    i++;
                }
            }

            var s = password.Aggregate("", (current, c) => current + char.ToLower(c));

            Console.WriteLine("Password = " + s);
        }
Beispiel #14
0
        public static async Task Prefix_(string args, IMessage message)
        {
            if (!(message.Channel is IGuildChannel))
            {
                await message.Channel.SendMessageAsync("This isn't a guild!"); return;
            }

            var guild       = (message.Channel as IGuildChannel).Guild;
            var guildHandle = Program.mainHandler.guildHandles[guild.Id];
            var badchars    = new char[] { ' ', ':', '\'', '"', '\n', '\r', '`' };

            if (args.Length > 0)
            {
                if (args.Any(n => badchars.Any(n.Equals)))
                {
                    await message.Channel.SendMessageAsync("There are some unrecommended characters, if the bot no longer is able to take commands, pass `$reset` to reset the prefix");

                    guildHandle.database.prefix = args;
                    guildHandle.helpEmbeds      = GuildHandler.GuildHandle.BuildEmbed(guildHandle.database.prefix);
                    await message.Channel.SendMessageAsync("Prefix set to `" + guildHandle.database.prefix + "`");
                }
                else
                {
                    guildHandle.database.prefix = args;
                    guildHandle.helpEmbeds      = GuildHandler.GuildHandle.BuildEmbed(guildHandle.database.prefix);
                    await message.Channel.SendMessageAsync("Prefix set to `" + guildHandle.database.prefix + "`");
                }
            }
            else
            {
                await message.Channel.SendMessageAsync("My prefix on this guild is `" + guildHandle.database.prefix + "`");
            }
        }
Beispiel #15
0
        public static void Main(string[] args)
        {
            int testCases = Convert.ToInt32(Console.ReadLine());

            char[] vowels    = new char[] { 'a', 'e', 'i', 'o', 'u' };
            char[] consonent = new char[] { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
            var    results   = new List <int>();

            for (int i = 0; i < testCases; i++)
            {
                int    length = Convert.ToInt32(Console.ReadLine());
                string input  = Console.ReadLine();
                int    count  = 0;
                for (int j = 0; j < length - 1; j++)
                {
                    if (consonent.Any(x => x == input[j]) && vowels.Any(x => x == input[j + 1]))
                    {
                        count++;
                    }
                }
                results.Add(count);
            }
            Console.WriteLine(string.Join(Environment.NewLine, results));
            Console.ReadLine();
        }
        /// <summary>
        /// Trims the end of the string.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="trimCharacters">The characters to trim.</param>
        /// <returns>The string builder minus the characters specified.</returns>
        public static StringBuilder?TrimEnd(this StringBuilder?builder, params char[] trimCharacters)
        {
            if (builder is null)
            {
                return(builder);
            }
            if (trimCharacters is null || trimCharacters.Length == 0)
            {
                trimCharacters = new char[] { ' ', '\t', '\n' }
            }
            ;
            var x = builder.Length;

            for (; x > 0; --x)
            {
                if (!trimCharacters.Any(y => builder[x - 1] == y))
                {
                    break;
                }
            }
            if (x == builder.Length)
            {
                return(builder);
            }
            builder.Remove(x, builder.Length - x);
            return(builder);
        }
        public override object GiveAnswer2()
        {
            var result = new char[8];

            for (var index = 0; result.Any(c => c == 0); index++)
            {
                var attempt = _password + index;
                var hash    = MD5.HashData(System.Text.Encoding.ASCII.GetBytes(attempt));
                if (hash[0] != 0 || hash[1] != 0 || hash[2] > 7 || result[hash[2]] != 0)
                {
                    continue;
                }
                var hexa = hash[3] >> 4;
                if (hexa < 10)
                {
                    result[hash[2]] = (char)('0' + hexa);
                }
                else
                {
                    result[hash[2]] = (char)('a' + hexa - 10);
                }
            }

            return(new string(result));
        }
        /// <summary>
        /// Trims the start of the string.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="trimCharacters">The characters to trim.</param>
        /// <returns>The builder with the values trimmed.</returns>
        public static StringBuilder?TrimStart(this StringBuilder?builder, params char[] trimCharacters)
        {
            if (builder is null)
            {
                return(builder);
            }
            if (trimCharacters is null || trimCharacters.Length == 0)
            {
                trimCharacters = new char[] { ' ', '\t', '\n' }
            }
            ;
            var x = 0;

            for (; x < builder.Length; ++x)
            {
                if (!trimCharacters.Any(y => builder[x] == y))
                {
                    break;
                }
            }
            if (x == 0)
            {
                return(builder);
            }
            builder.Remove(0, x);
            return(builder);
        }
    }
Beispiel #19
0
    private IEnumerable <object> ProcessAlphabeticalRuling(KMBombModule module)
    {
        var comp      = GetComponent(module, "AlphabeticalRuling");
        var fldSolved = GetField <bool>(comp, "solved");
        var fldStage  = GetIntField(comp, "currentStage");

        while (!_isActivated)
        {
            yield return(new WaitForSeconds(.1f));
        }

        var letterDisplay  = GetField <TextMesh>(comp, "LetterDisplay", isPublic: true).Get();
        var numberDisplays = GetArrayField <TextMesh>(comp, "NumberDisplays", isPublic: true).Get(expectedLength: 2);
        var curStage       = 0;
        var letters        = new char[3];
        var numbers        = new int[3];

        while (!fldSolved.Get())
        {
            var newStage = fldStage.Get();
            if (newStage != curStage)
            {
                if (letterDisplay.text.Length != 1 || letterDisplay.text[0] < 'A' || letterDisplay.text[0] > 'Z')
                {
                    throw new AbandonModuleException("‘LetterDisplay’ shows {0} (expected single letter A–Z).", letterDisplay.text);
                }
                letters[newStage - 1] = letterDisplay.text[0];
                int number;
                if (!int.TryParse(numberDisplays[0].text, out number) || number < 1 || number > 9)
                {
                    throw new AbandonModuleException("‘NumberDisplay[0]’ shows {0} (expected integer 1–9).", numberDisplays[0].text);
                }
                numbers[newStage - 1] = number;
                curStage = newStage;
            }

            yield return(null);
        }
        _modulesSolved.IncSafe(_AlphabeticalRuling);

        if (letters.Any(l => l < 'A' || l > 'Z') || numbers.Any(n => n < 1 || n > 9))
        {
            throw new AbandonModuleException("The captured letters/numbers are unexpected (letters: [{0}], numbers: [{1}]).", letters.JoinString(", "), numbers.JoinString(", "));
        }

        var qs = new List <QandA>();

        for (var ix = 0; ix < letters.Length; ix++)
        {
            qs.Add(makeQuestion(Question.AlphabeticalRulingLetter, _AlphabeticalRuling, formatArgs: new[] { ordinal(ix + 1) }, correctAnswers: new[] { letters[ix].ToString() }));
        }
        for (var ix = 0; ix < numbers.Length; ix++)
        {
            qs.Add(makeQuestion(Question.AlphabeticalRulingNumber, _AlphabeticalRuling, formatArgs: new[] { ordinal(ix + 1) }, correctAnswers: new[] { numbers[ix].ToString() }));
        }
        addQuestions(module, qs);
    }
        private string iiiiiiii(string inputValue)
        {
            var vowels       = new char[] { 'a', 'e', 'o', 'u' };
            var UpperVowels  = new char[] { 'A', 'E', 'O', 'U' };
            var AccentVowels = new char[] { 'á', 'é', 'ó', 'ú' };

            inputValue = new string(inputValue.ToCharArray().Select(x => vowels.Any(y => y == x) ? 'i' : x).ToArray());
            inputValue = new string(inputValue.ToCharArray().Select(x => UpperVowels.Any(y => y == x) ? 'I' : x).ToArray());
            inputValue = new string(inputValue.ToCharArray().Select(x => AccentVowels.Any(y => y == x) ? 'í' : x).ToArray());
            return(inputValue);
        }
Beispiel #21
0
        private void EnforceInvariants(char directionName)
        {
            char[] directions = new char[4] {
                'n', 'e', 's', 'w'
            };

            if (!directions.Any(x => x.Equals(char.ToLower(directionName))))
            {
                throw new ArgumentOutOfRangeException("oreintation must have valid initial of direction.");
            }
        }
        // *** METHODS ***

        /// <summary>
        /// Parses a notation string into a LayerMove
        /// </summary>
        /// <param name="notation">Defines to string to be parsed</param>
        /// <returns></returns>
        public static LayerMove Parse(string notation)
        {
            string   layer         = notation[0].ToString();
            CubeFlag rotationLayer = CubeFlagService.Parse(layer);

            char[] ccwChars  = new char[] { '\'', 'i' };
            bool   direction = !ccwChars.Any(c => notation.Contains(c));

            bool twice = notation.Contains("2");

            return(new LayerMove(rotationLayer, direction, twice));
        }
Beispiel #23
0
        private static string GetMessageText(string expectedOutput, string output)
        {
            string result = "";

            char[] wildCardChars = new char[] { '[', ']', '?', '*', '#' };
            if (wildCardChars.Any(c => expectedOutput.Contains(c)))
            {
                result += "NOTE: The expected string contains wildcard charaters: [,],?,*,#" + Environment.NewLine;
            }
            if (expectedOutput.Contains(Environment.NewLine))
            {
                result += string.Join(Environment.NewLine, "AreEqual failed:", "",
                                      "Expected:", "-----------------------------------", expectedOutput, "-----------------------------------",
                                      "Actual: ", "-----------------------------------", output, "-----------------------------------");
            }
            else
            {
                result += string.Join(Environment.NewLine, "AreEqual failed:",
                                      "Expected: ", expectedOutput,
                                      "Actual:   ", output);
            }

            int expectedOutputLength = expectedOutput.Length;
            int outputLength         = output.Length;

            if (expectedOutputLength != outputLength)
            {
                result += $"{Environment.NewLine}The expected length of {expectedOutputLength} does not match the output length of {outputLength}. ";
                string[] items = (new string[] { expectedOutput, output }).OrderBy(item => item.Length).ToArray();
                if (items[1].StartsWith(items[0]))
                {
                    result += $"{Environment.NewLine}The additional characters are '"
                              + $"{CSharpStringEncode(items[1].Substring(items[0].Length))}'.";
                }
            }
            else
            {
                // Write the output that shows the difference.
                for (int counter = 0; counter < Math.Min(expectedOutput.Length, output.Length); counter++)
                {
                    if (expectedOutput[counter] != output[counter]) // TODO: The message is invalid when using wild cards.
                    {
                        result += Environment.NewLine
                                  + $"Character {counter} did not match: "
                                  + $"'{CSharpStringEncode(expectedOutput[counter])}' != '{CSharpStringEncode(output[counter])})'";
                        ;
                        break;
                    }
                }
            }

            return(result);
        }
Beispiel #24
0
        public static string CreateRandomPassword(int length = 12)
        {
            // Create a string of characters, numbers, three special characters that are allowed in the password
            string validChars   = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&?!";
            string digits       = "0123456789";
            string specialChars = "&?!_@$#";
            string upperChars   = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
            string lowerChars   = "abcdefghijklmnopqrstuvwxyz";
            Random random       = new Random();

            // Select one random character at a time from the string and create an array of chars
            char[] chars = new char[length];
            for (int i = 0; i < length; i++)
            {
                chars[i] = validChars[random.Next(0, validChars.Length)];
            }

            if (!chars.Any(x => char.IsDigit(x)))
            {
                chars[length - 1] = digits[random.Next(0, digits.Length)];
            }

            if (!chars.Any(x => specialChars.Contains(x)))
            {
                chars[length - 2] = specialChars[random.Next(0, specialChars.Length)];
            }

            if (!chars.Any(x => char.IsLower(x)))
            {
                chars[length - 3] = lowerChars[random.Next(0, lowerChars.Length)];
            }

            if (!chars.Any(x => char.IsUpper(x)))
            {
                chars[length - 4] = upperChars[random.Next(0, upperChars.Length)];
            }

            return(new string(chars));
        }
        /// <summary>
        /// Escapes a column's name.
        /// </summary>
        /// <param name="columnName">The name of the column to escape.</param>
        /// <returns>The escaped <paramref name="columnName"/>.</returns>
        /// <exception cref="InvalidQueryException"><paramref name="columnName"/> is an invalid column name.</exception>
        public string EscapeColumn(string columnName)
        {
            var skipChars = new char[] { '.', '(', ')', ' ' };

            if (!skipChars.Any(x => columnName.Contains(x)))
            {
                return("`" + columnName + "`");
            }
            else
            {
                return(columnName);
            }
        }
        /// <summary>
        /// Escapes a table's name.
        /// </summary>
        /// <param name="tableName">The name of the table to escape.</param>
        /// <returns>The escaped <paramref name="tableName"/>.</returns>
        /// <exception cref="InvalidQueryException"><paramref name="tableName"/> is an invalid table name.</exception>
        public string EscapeTable(string tableName)
        {
            var skipChars = new char[] { '.', '(', ')', ' ' };

            if (!skipChars.Any(x => tableName.Contains(x)))
            {
                return("`" + tableName + "`");
            }
            else
            {
                return(tableName);
            }
        }
        private bool HasIllegalChars(string[] segments)
        {
            // wildchar is only allowed inside the last segment
            var illegal = new char[] { '*', '?' };

            for (var i = 0; i < segments.Length - 1; ++i)
            {
                if (illegal.Any(segments[i].Contains))
                {
                    return(true);
                }
            }
            return(false);
        }
        private static string ChangeVocals(string str)
        {
            var vocalChar = new char[]
            {
                'a', 'i', 'u', 'e', 'o',
                'A', 'i', 'U', 'E', 'O'
            };

            return(string.Concat(str.Select(character =>
            {
                return vocalChar.Any(item => item == character)
                    ? (char)((int)character + 1)
                    : character;
            })));
        }
Beispiel #29
0
        public static void SetUpMatchers()
        {
            char[] command = new char[] { '.', '$', '!', '?', '>' };

            foreach (var pair in Commands)
            {
                if (!command.Any(c => pair.Key.StartsWith(c.ToString())))
                {
                    AddMatcher(pair.Key, pair.Key, MatchType.Contains, false, false);
                }
                else
                {
                    AddMatcher(pair.Key, pair.Key, MatchType.StartsWith, pair.Key.StartsWith("$"));
                }
            }
        }
        ParseToNumberAndOperations(IEnumerable <string> splitedIntoOperationsAndNumbers)
        {
            var collectionLength = splitedIntoOperationsAndNumbers.Count();
            var numbers          = new List <uint>();
            var operations       = new List <MathOperationType>();
            var operationChars   = new char[] { '+', '-', '*', '/' };

            for (var index = 0; index < collectionLength; index++)
            {
                try
                {
                    if (index % 2 == 0)
                    {
                        numbers.Add(uint.Parse(splitedIntoOperationsAndNumbers.ElementAt(index)));
                    }
                    else
                    {
                        if (index == collectionLength - 1)
                        {
                            throw new ArgumentException("Last value must be a number.");
                        }

                        var operationChar = char.Parse(splitedIntoOperationsAndNumbers.ElementAt(index));
                        if (!operationChars.Any(x => x == operationChar))
                        {
                            throw new ArgumentException($"Element:{splitedIntoOperationsAndNumbers.ElementAt(index)}" +
                                                        $"is not a operation.");
                        }
                        operations.Add((MathOperationType)operationChar);
                    }
                }
                catch (OverflowException e)
                {
                    throw new ArgumentException("Value provided is out of range.", e);
                }
                catch (FormatException e)
                {
                    throw new ArgumentException(
                              "Math operation does not meet the template requirement. " +
                              "Number Operation etc.. Number", e);
                }
            }

            return(numbers, operations);
        }