コード例 #1
0
        static void Main(string[] args)
        {
            Random rnd  = new Random();
            var    nums = new int[10000];

            for (int count = 0; count < 10; count++)
            {
                for (int i = 0; i < nums.Length; i++)
                {
                    nums[i] = rnd.Next(1, 10000);
                }

                var result = MergeSort.Sort(nums, (a, b) => a - b);
                // LINQのOrderByメソッドの結果と比較することで、MergeSortが正しく整列されているかを確認している
                bool isEqual = Enumerable.SequenceEqual(result, nums.OrderBy(n => n));
                Console.WriteLine(isEqual);
            }
            Console.WriteLine("end");
        }
コード例 #2
0
        private void SortArrayClick(object sender, RoutedEventArgs e)
        {
            FlipView.Items.Clear();
            int i = 0;

            //Checks if all members are numbers
            bool allAreNumber = true;

            for (int j = 0; j < sample.Count; j++)
            {
                if (!int.TryParse(sample[i], out int num))
                {
                    allAreNumber = false;
                }
            }
            //If all are numbers, convert
            int[] sampleintarray = new int[sample.Count];
            if (allAreNumber)
            {
                for (int j = 0; j < sample.Count; j++)
                {
                    sampleintarray[j] = Convert.ToInt32(sample[j]);
                }

                var tempresult = MergeSort <int> .Do(sampleintarray);

                Result = new string[sampleintarray.Length];
                var tempHistory = MergeSort <int> .History;
                for (int j = 0; j < tempresult.Length; j++)
                {
                    Result[j] = tempresult[j].ToString();
                }
                History.Clear();
                foreach (int[] ints in tempHistory)
                {
                    string[] tempstep = new string[ints.Length];
                    for (int j = 0; j < ints.Length; j++)
                    {
                        tempstep[j] = ints[j].ToString();
                    }

                    History.Add(tempstep);
                }
            }
            else
            {
                Result = MergeSort <string> .Do(sample.ToArray());

                History = MergeSort <string> .History;
            }

            sample            = Result.ToList();
            Array.ItemsSource = sample;
            var x = CreateFlipViews();

            foreach (FlipViewItem flipViewItem in x)
            {
                FlipView.Items.Add(flipViewItem);
            }

            FlipView.SelectedIndex = 0;

            yourMahAppFlyout.IsOpen = false;
        }
コード例 #3
0
        static public void CheckCorrectArgs(string[] userInput)
        {
            //блок экземпляров для чисел
            ReadInputFiles  inputIntCollection = new ReadInputFiles();
            MergeSort <int> EndResultInt       = new MergeSort <int>();
            List <int>      resultSort         = new List <int>();

            //блок экземпляров для строк
            ReadInputFilesString inputStringCollectionString = new ReadInputFilesString();
            MergeSort <string>   EndResultString             = new MergeSort <string>();
            List <string>        resultSortString            = new List <string>();

            int  i    = 0;
            bool flag = true;

            while (flag == true && i < userInput.Length)
            {
                if (userInput[i] == "-help")
                {
                    ShowManual();
                    break;
                }
                if (userInput.Length < 5)
                {
                    Console.WriteLine("Указано недопустимое количество параметров.При запуске обязательно указать:" +
                                      "\n 1) Тип данных для сортировки \n 2) Имя выходного файла \n 3) Имя выходного файла. " + "4)Имя входного файла 1. \n5) Имя входного файла 2." +
                                      "\nПрочитайте инструкцию и перезапустите программу, указав верное значение аргументов\n");
                    ShowManual();
                    flag = false;
                }
                else
                {
                    switch (userInput[0])
                    {
                    case "-d":
                        Condition1Args(userInput[0], userInput);
                        break;

                    case "-a":
                        Condition1Args(userInput[0], userInput);
                        break;

                    default:
                        Console.WriteLine(" Введено неверное значение 1 - го аргумента." +
                                          "\n Аргумент 1 должен содержать:" +
                                          "\n 1) Режим сортировки. Обязательный к указанию. Принимаемые парметры : '-d' = сортировка по возрастанию '-a' = сортировка по убыванию" +
                                          "\nПрочитайте инструкцию и перезапустите программу, указав верное значение аргументов\n");
                        ShowManual();
                        flag = false;
                        break;
                    }
                }
                //Вызов инструкции для корректного запуска программы
                void ShowManual()
                {
                    Console.WriteLine("Добрый день! Сразу к делу! \nДля корректного запуска программы неободимо ввести верную последовательность аругментов " +
                                      "\n 1) Тип сортировки (Обязательный аргумент). \nУказываемые парметры: \n '-d' - сотрировка по возрастанию. \n '-a' - сортировка по убыванию " +
                                      "\n2) Тип сортируемых данных (Обязательный аргумент). \nУказываемые параметры: \n '-s' - тип string. \n '-i' - тип int." +

                                      "\n3) Имя выходного файла. Если имя не будет указано, то файл будет создан автоматически и будет ему имя 'output.txt' " +
                                      "\n4) Имя вхожного файла 1. Имя файла должно быть 'inpit1.txt'" +
                                      "\n5)  Имя вхожного файла 1. Имя файла должно быть 'inpit2.txt'"
                                      );
                }
            }
            //метод который работает с аргументами, если не будет четкого соблюдения, то напишет ошибку. Также если все хорошо, то будет отражен конечный результат
            void Condition1Args(string arg0, string[] args)
            {
                try
                {
                    if (args[1] == "-s")
                    {
                        if (args[3] == "input1.txt" && args[4] == "input2.txt")
                        {
                            if (arg0 == "-d")
                            {
                                resultSortString = EndResultString.Sort(inputStringCollectionString.GetString(userInput[3], userInput[4]));
                                File.WriteAllLines(userInput[2], resultSortString);
                                Console.WriteLine($"Данные успешно записаны в файл: {userInput[2]}");
                                flag = false;
                            }
                            else
                            {
                                resultSortString = EndResultString.Sort(inputStringCollectionString.GetString(userInput[3], userInput[4]));
                                resultSortString.Reverse(); // переворачиваем содержимое из-за того что пользователь ввел аргумент -а
                                File.WriteAllLines(userInput[2], resultSortString);
                                Console.WriteLine($"Данные успешно записаны в файл: {userInput[2]}");
                                flag = false;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Неверный аргумент 4 или 5. \nПерезапустите программу только с одним аргументом '-help' чтобы прочитать инструкцию по запуску.Вероятно указанные входные файлы не найдены");
                            flag = false;
                        }
                    }
                    else if (args[1] == "-i")
                    {
                        if (args[3] == "input1.txt" && args[4] == "input2.txt")
                        {
                            if (arg0 == "-d")
                            {
                                resultSort = EndResultInt.Sort(inputIntCollection.GetInt(userInput[3], userInput[4]));
                                File.WriteAllLines(userInput[2], ConvertToString(resultSort));
                                Console.WriteLine($"Данные успешно записаны в файл: {userInput[2]}");

                                flag = false;
                            }
                            else
                            {
                                resultSort = EndResultInt.Sort(inputIntCollection.GetInt(userInput[3], userInput[4]));
                                resultSort.Reverse();    // переворачиваем содержимое из-за того что пользователь ввел аргумент -а
                                File.WriteAllLines(userInput[2], ConvertToString(resultSort));
                                Console.WriteLine($"Данные успешно записаны в файл: {userInput[2]}");
                                flag = false;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Неверный аргумент 4 или 5. Перезапустите программу только с одним аргументом '-help' чтобы прочитать инструкцию по запуску.Вероятно указанные входные файлы не найдены");
                            flag = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Неверный аргумент 2. Перезапустите программу только с одним аргументом '-help' чтобы прочитать инструкцию по запуску.");
                        flag = false;
                    }
                }
                catch (FormatException ex)
                {
                    Console.WriteLine($"Вызвано исключение: {ex.Message}. \nВ одном из входных файлов присутствует неверный тип данных. Проверьте входные файлы на однородность типов данных и перезапустите программу!");
                    flag = false;
                }
            }

            // метод конверитрует все символы в в строки из-за особенностей метода File.AllWriteLines.
            List <string> ConvertToString(List <int> items)
            {
                List <string> result1 = new List <string>();

                for (int j = 0; j < items.Count; j++)
                {
                    result1.Add(items[j].ToString());
                }
                return(result1);
            }
        }
コード例 #4
0
        static void Main(string[] args)
        {
            Random    rnd      = new Random();
            const int MAX_SIZE = 64;
            Boolean   isValid;                       //=> do loop flag
            int       size = 0;                      //=> size of array

            int[]  arr;                              //=> array
            string range;                            //=> range input

            string[] bounds;                         //=> split range input
            int      upperBound = 0, lowerBound = 0; //=> range bounds
            string   message = "Welcome to Merge Sort in C#";

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine(message);

            do                              //=> input entry for array size
            {
                Console.ForegroundColor = ConsoleColor.White;
                isValid = false;
                Console.WriteLine("\nPlease enter an array size that is greater than 0 and less than or equal to {0}:", MAX_SIZE);

                try {                       //=> guard against non-numeric data
                    size = Convert.ToInt32(Console.ReadLine());

                    try {                   //=> guard against invalid array size
                        if (size <= 0)
                        {
                            throw new OverflowException();
                        }

                        try {
                            if (size > MAX_SIZE)
                            {
                                throw new OverflowException();
                            }

                            isValid = true;
                        } catch (OverflowException e) {
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            Console.WriteLine(".. Invaild input, {0} is larger than {1}.\n", size, MAX_SIZE);
                        }
                    }
                    catch (OverflowException e) {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine(".. Invaild input, you cannot have an array of size {0}.\n", size);
                    }
                } catch (FormatException e) {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(".. Invaild input, input must be of TYPE integer.\n");
                }
            } while (isValid != true);

            do                              //=> input entry for element range
            {
                Console.ForegroundColor = ConsoleColor.White;
                isValid = false;

                Console.WriteLine("\nPlease enter a range (integer values only) lower bound <space> upper bound:");
                range  = Console.ReadLine();
                bounds = range.Split(' ', '\t');

                try {                       //=> check for correct range format (two values)
                    if (bounds.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException();
                    }

                    try {                   //=> guard against non-numeric data
                        lowerBound = Convert.ToInt32(bounds[0]);
                        upperBound = Convert.ToInt32(bounds[1]);


                        try {               //=> guard against non-ascending range
                            if (upperBound < lowerBound)
                            {
                                throw new Exception();
                            }
                            else
                            {
                                isValid = true;
                            }
                        } catch (Exception e) {
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            Console.WriteLine(".. Invaild input, lower bound({0}) is larger than upper bound({1}).\n", lowerBound, upperBound);
                        }
                    } catch (FormatException e) {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine(".. Invaild input, both inputs must be of TYPE integer.\n");
                    }
                } catch (ArgumentOutOfRangeException e) {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(".. Invalid range, range requires two values.\n");
                }
            } while (isValid != true);

            arr = new int[size];                        //=> instantiate the array

            for (int i = 0; i < arr.Length; i++)        //=> populate the array
            {
                arr[i] = rnd.Next(lowerBound, upperBound);
            }

            Console.WriteLine("\n\n> Status: Unsorted\n> Timestamp: {0}\n> Type: {1}\n> Size: {2}\n> Range: {3} to {4}\n", DateTime.Now, arr.GetType(), size, lowerBound, upperBound);
            MergeSort.displayArray(arr, arr.Length);    //=> display the unsorted array

            MergeSort.mergeSort(arr, arr.Length);       //=> sort the array using mergeSort

            Console.WriteLine("\n\n> Status: Sorted\n> Timestamp: {0}\n> Merge Sort (recursive)\n> Type: {1}\n> Size: {2}\n> Range: {3} to {4}\n", DateTime.Now, arr.GetType(), size, lowerBound, upperBound);
            MergeSort.displayArray(arr, arr.Length);    //=> display the sorted array
        }