コード例 #1
0
ファイル: algorithm.cs プロジェクト: takla21/Practice
        private static List <string> DigitalWordGenerator(int[] digits)
        {
            var    file         = new System.IO.StreamReader("../../resources/4letterword.txt");
            var    stateMachine = new StateMachine('0');
            string word;

            while ((word = file.ReadLine()) != null)
            {
                stateMachine.AddElement(word);
            }
            file.Close();

            var digitToLetters = new Dictionary <int, char[]>()
            {
                { 2, new char[] { 'a', 'b', 'c' } },
                { 3, new char[] { 'd', 'e', 'f' } },
                { 4, new char[] { 'g', 'h', 'i' } },
                { 5, new char[] { 'j', 'k', 'l' } },
                { 6, new char[] { 'm', 'n', 'o' } },
                { 7, new char[] { 'p', 'q', 'r', 's' } },
                { 8, new char[] { 't', 'u', 'v' } },
                { 9, new char[] { 'w', 'y', 'y', 'z' } }
            };

            var letters = new char[4][];

            for (int i = 0; i < digits.Length; i++)
            {
                if (digitToLetters.ContainsKey(digits[i]))
                {
                    letters[i] = digitToLetters[digits[i]];
                }
                else
                {
                    throw new Exception($"{digits[i]} is not a valid digit");
                }
            }

            string composeWord = "";
            var    validWords  = new List <string>();

            for (int i = 0; i < letters[0].Length; i++)
            {
                composeWord += letters[0][i];
                for (int j = 0; j < letters[1].Length; j++)
                {
                    composeWord += letters[1][j];
                    for (int k = 0; k < letters[2].Length; k++)
                    {
                        composeWord += letters[2][k];
                        for (int l = 0; l < letters[3].Length; l++)
                        {
                            composeWord += letters[3][l];
                            if (stateMachine.ValidWord(composeWord))
                            {
                                validWords.Add(composeWord);
                            }
                            composeWord = composeWord.Substring(0, composeWord.Length - 1);
                        }
                        composeWord = composeWord.Substring(0, composeWord.Length - 1);
                    }
                    composeWord = composeWord.Substring(0, composeWord.Length - 1);
                }
                composeWord = composeWord.Substring(0, composeWord.Length - 1);
            }

            return(validWords);
        }