private static bool Test4(ISortingAlgorithm sort) { string testname = sort.GetSortName() + " Test 4"; int[] arr1 = new int[] { 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // array to check return(Test(testname, sort, arr1)); }
public void Execute() { SortingType sortingType = GetSortingType(); if (sortingType == SortingType.Exit) { return; } ISortingAlgorithm algorithm = GetSortingAlgorithm(sortingType); Console.WriteLine("What's the input file name?"); string inputFilename = Console.ReadLine(); string[] linesIn = File.ReadAllLines(inputFilename); Console.WriteLine("What's the output file name?"); string outputFilename = Console.ReadLine(); Stopwatch stopWatch = new Stopwatch(); string[] linesOut; Console.WriteLine("Sorting..."); double[] items = linesIn.Select(line => double.Parse(line)).ToArray(); stopWatch.Start(); algorithm.Sort(items); stopWatch.Stop(); linesOut = items.Select(item => item.ToString()).ToArray(); File.WriteAllLines(outputFilename, linesOut); ProgramUtils.WriteLineImpressive($"Succesfully sorted the values in {inputFilename} and wrote the result to {outputFilename} in {stopWatch.ElapsedMilliseconds} ms"); }
public static bool StoreRun(ISortingAlgorithm algorithm) { string connectionString = File.ReadAllText("Data/conn.txt"); MySqlConnection connection = new MySqlConnection(connectionString); MySqlCommand command = new MySqlCommand(); try{ connection.Open(); command.CommandType = System.Data.CommandType.StoredProcedure; command.Connection = connection; command.CommandText = "insertNewRun"; command.Parameters.Add(new MySqlParameter("iAName", algorithm.Name)); command.Parameters.Add(new MySqlParameter("iTimeNotation", algorithm.TimeNotation)); command.Parameters.Add(new MySqlParameter("iSpaceNotation", algorithm.SpaceNotation)); command.Parameters.Add(new MySqlParameter("iRunStart", algorithm.RunStart)); command.Parameters.Add(new MySqlParameter("iRunEnd", algorithm.RunEnd)); command.Parameters.Add(new MySqlParameter("iTotalTime", algorithm.TotalTime.TotalMilliseconds)); command.Parameters.Add(new MySqlParameter("iEntries", algorithm.Entries)); command.ExecuteNonQuery(); return(true); } catch (Exception e) { System.Console.WriteLine(e); return(false); } finally{ connection.Close(); GC.Collect(); } }
private static bool Test5(ISortingAlgorithm sort) { string testname = sort.GetSortName() + " Test 5"; int[] arr1 = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // array to check return(Test(testname, sort, arr1)); }
private static bool Test6(ISortingAlgorithm sort) { string testname = sort.GetSortName() + " Test 6"; int[] arr1 = new int[] { 564, 854, 789, 513, 156, 758, 756, 958, 3215 }; // array to check return(Test(testname, sort, arr1)); }
public async Task Execute(string[] args) { await Parser.Default.ParseArguments <Options>(args).MapResult(async(Options opts) => { ISortingAlgorithm algorithm = GetSortingAlgorithm(opts.sortingAlgorithm); string[] linesIn = File.ReadAllLines(opts.inputFile); Stopwatch stopWatch = new Stopwatch(); string[] linesOut; Console.WriteLine("Sorting..."); double[] items = linesIn.Select(line => double.Parse(line)).ToArray(); stopWatch.Start(); if (opts.parallel) { await algorithm.SortParallel(items); } else { algorithm.Sort(items); } stopWatch.Stop(); linesOut = items.Select(item => item.ToString()).ToArray(); File.WriteAllLines(opts.outputFile, linesOut); ProgramUtils.WriteLineImpressive($"Succesfully sorted the values in {opts.inputFile} and wrote the result to {opts.outputFile} in {stopWatch.ElapsedMilliseconds} ms"); return(1); }, (_) => Task.FromResult(0)); }
private static void DisplaySortingResults(ISortingAlgorithm sortingAlgorithm, long executionTime) { Console.Write(Environment.NewLine); Console.WriteLine("-------------------------"); Console.WriteLine($"Memory usage: {Process.GetCurrentProcess().PrivateMemorySize64 / 1048} KB"); Console.WriteLine($"{sortingAlgorithm.GetType().UnderlyingSystemType.Name} completed. Time elapsed: {executionTime} ms"); Console.WriteLine("-------------------------"); Console.Read(); }
static void DisplayProducts(List <Product> products, ISortingAlgorithm <List <Product> > sorter) { sorter.Sort(products); // display foreach (Product p in products) { Console.WriteLine(p); } }
IEnumerator createTriggersAndBoxes() { solved = false; GetComponent <ResizeTable>().updateTableSize(boxesToSort); sortBoxes = new GameObject[boxesToSort]; sortBoxTriggers = new GameObject[boxesToSort]; sortingAlgorithm = new BubbleSort(); sortingAlgorithm.ArrayToSort = createRandomArray(); int j = 0; foreach (int i in sortingAlgorithm.ArrayToSort) { GameObject box = Instantiate(sortBox, boxSpawnPoint.transform); SortBoxScript sortBoxScript = box.GetComponent <SortBoxScript>(); if (sortBoxScript) { sortBoxScript.SetNumbersVisible(isNumbersVisible); sortBoxScript.SetGrabbable(j == leftIndex || j == rightIndex); } GameObject boxTrigger = Instantiate(sortBoxTrigger, boxSpawnPoint.transform); boxTrigger.transform.localPosition += new Vector3(0, 0, j * boxTrigger.transform.localScale.z * 1.1f); //boxTrigger.GetComponent<SortBoxTriggerScript>().correctValue = i; //Debug.Log("Does this run on restart?"); box.transform.localPosition += new Vector3(0, 0, j * boxTrigger.transform.localScale.z * 1.1f); boxTrigger.GetComponent <SortBoxHandler>().SetActive(true); //TODO: This stuff should probably be placed on SortBoxScript instead. box.GetComponent <SortBoxScript>().value = i; foreach (TextMeshPro tmPro in box.GetComponentsInChildren <TextMeshPro>()) { tmPro.text = i.ToString(); } sortBoxes[j] = box; sortBoxTriggers[j] = boxTrigger; j++; yield return(null); } triggerLeft = sortBoxTriggers[leftIndex].GetComponent <SortBoxTriggerScript>(); triggerRight = sortBoxTriggers[rightIndex].GetComponent <SortBoxTriggerScript>(); if (triggerLeft && triggerRight) { boxLeft = triggerLeft.GetObjectInTrigger().GetComponent <SortBoxScript>(); boxRight = triggerRight.GetObjectInTrigger().GetComponent <SortBoxScript>(); } //sortBoxTriggers[j - sortingAlgorithm.CurrentStep() - 1].GetComponent<SortBoxTriggerScript>().isFinal = true; updateTriggers(); if (!isShowingGeneralInstructions) { instructionWall.GetComponentInChildren <TextMeshPro>().text = sortingAlgorithm.GetInstruction(); } tableExist = true; }
private static bool Test(string testname, ISortingAlgorithm sort, int[] arr1) { int[] _sort() { return(sort.Sort(arr1)); } CallSort <int> delSort = new CallSort <int>(_sort); return(Test(testname, delSort, arr1)); }
private void TestRandomInts(ISortingAlgorithm sort) { /* Randomize numbers 0..49 */ IComparable[] a = Enumerable.Range(0, 50).OrderBy(r => rnd.Next()).Select(x => x as IComparable).ToArray(); sort.Sort(ref a); /* Make sure they are sorted */ for (int i = 1; i < a.Length; i++) { Assert.AreEqual(true, a[i - 1].CompareTo(a[i]) < 0); } }
static void SortList(List<int> list, ISortingAlgorithm sortingAlgorithm) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); sortingAlgorithm.Sort<List<int>, int>(list, Comparer<int>.Default); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime + "\n"); }
private static void Profile(ISortingAlgorithm <int> sortingAlgorithm) { Logger.Default.Log(LogLevel.Debug, $"Profiling {sortingAlgorithm.GetType().Name}"); int[] numbers = GenerateNumbers(); Stopwatch stopwatch = Stopwatch.StartNew(); sortingAlgorithm.Sort(numbers); stopwatch.Stop(); Logger.Default.Log(LogLevel.Trace, $"Results: {stopwatch.ElapsedTicks} ticks; {stopwatch.ElapsedMilliseconds} ms ({stopwatch.Elapsed:T})"); }
public static void Sort <T>(this T[] arrayToSort, ISortingAlgorithm <T> sortingAlgorithm) where T : IComparable <T> { if (arrayToSort is null) { throw new ArgumentNullException(nameof(arrayToSort)); } if (sortingAlgorithm is null) { throw new ArgumentNullException(nameof(sortingAlgorithm)); } sortingAlgorithm.Sort(arrayToSort); }
public static void WriteRun(ISortingAlgorithm algorithm, string path) { using (StreamWriter sw = new StreamWriter(path, true)){ sw.WriteLine("----------------------------------------------------"); sw.WriteLine("Algoritmo: " + algorithm.Name); sw.WriteLine("Horario de ínicio da execução: " + algorithm.RunStart); sw.WriteLine("Horário de Término da execução: " + algorithm.RunEnd); sw.WriteLine("Tempo total de execução: " + algorithm.TotalTime); sw.WriteLine("Número de elementos ordenados: " + algorithm.Entries); sw.WriteLine("Notação de Tempo média do Algoritmo: " + algorithm.TimeNotation); sw.WriteLine("Notação de Espaço média do Algoritmo: " + algorithm.SpaceNotation); sw.WriteLine("----------------------------------------------------"); } }
public void Sort <T>(ISortingAlgorithm <T> algorithm, T[] items) where T : IComparable <T> { if (items == null) { throw new ArgumentNullException(); } if (items.Length == 0) { throw new ArgumentOutOfRangeException(); } algorithm.Sort(items); }
private void Sort(int[] intTempArray, SortType sortType, CancellationToken cToken, HSBColor[] floatSortArray, bool hsb, int delay) { ISortingAlgorithm sortingAlgorithm = null; switch (sortType) { case SortType.QuickSort: sortingAlgorithm = new QuickSortAlgorithm(); break; case SortType.BubbleSort: sortingAlgorithm = new BubbleSortAlgorithm(); break; case SortType.HeapSort: sortingAlgorithm = new HeapSortAlgorithm(); break; case SortType.SelectionSort: sortingAlgorithm = new SelectionSortAlgorithm(); break; case SortType.MergeSort: sortingAlgorithm = new MergeSortAlgorithm(); break; break; case SortType.ParalellMergeSort: sortingAlgorithm = new ParalellMergeSortAlgorithm(); break; } sortingAlgorithm.Token = cToken; sortingAlgorithm.Delay = delay; if (hsb) { sortingAlgorithm.Sort(intTempArray, floatSortArray); } else { sortingAlgorithm.Sort(intTempArray); } }
private static void TestSortingAlgorithm(ISortingAlgorithm algorithm, int maxArraySize, int numberOfTest) { Stopwatch stopwatch = new Stopwatch(); for (int arraySize = 10; arraySize <= maxArraySize; arraySize *= 10) { for (int n = 0; n <= numberOfTest; n++) { int[] array = GenerateRandomArray(arraySize); stopwatch.Start(); algorithm.Sort(array); stopwatch.Stop(); Console.WriteLine(string.Format("'{0}', SortingBy: '{1}', ElapsedTime: '{2}', N: '{3}'", algorithm.GetType().Name, SortingBy(array), stopwatch.Elapsed, array.Length)); stopwatch.Reset(); } } }
private static bool TestRandom(ISortingAlgorithm sort) { int nFrom = 0; int nTo = 100; Random rand = new Random(); int numTests = sort.numberOfTests; int n = 0; double[] arr; int[] arr1; string testname = sort.GetSortName() + " Test"; for (int i = 0; i < numTests; i++) { n = rand.Next(nFrom, nTo); if (sort.allowsDecimals) { arr = new double[n]; for (int j = 0; j < n; j++) { arr[j] = rand.NextDouble() * (double)sort.ToRandomRange; } if (!Test(testname + " " + i.ToString(), sort, arr)) { return(false); } } else { arr1 = new int[n]; for (int j = 0; j < n; j++) { arr1[j] = rand.Next(sort.FromRandomRange, sort.ToRandomRange); } if (!Test(testname + " " + i.ToString(), sort, arr1)) { return(false); } } } return(true); }
private bool TestDefault(ISortingAlgorithm sort) { Random rand = new Random(); List <TestCase> cases = new List <TestCase>(); cases.Add(Test1); cases.Add(Test2); cases.Add(Test3); cases.Add(Test4); cases.Add(Test5); cases.Add(Test6); foreach (TestCase test in cases) { if (!test.Invoke(sort)) { return(false); } } return(true); }
public static void SubMain(ISortingAlgorithm sortingAlgorithm) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); int elementCount = 25000; int[] Array = new int[elementCount]; Random random = new Random(); for (int i = 0; i < elementCount - 1; i++) { int randomSayi = random.Next(1, 9999); Array[i] = randomSayi; } int[] siralanmisArray = sortingAlgorithm.SortASC(Array); stopwatch.Stop(); Console.WriteLine("------------------------------------------------------------"); Console.WriteLine(sortingAlgorithm.Name + " | " + stopwatch.ElapsedMilliseconds); Console.WriteLine(string.Join(",", siralanmisArray)); }
/// <summary> /// Sort a small text file. /// </summary> /// <param name="streamName">The name of the file to sort.</param> /// <param name="sortingAlgorithm">The algorithm to use for sorting.</param> /// <returns>The sorted items.</returns> public static string[] SortCommon(string streamName, ISortingAlgorithm sortingAlgorithm) { Contract.Ensures(null != Contract.Result<string[]>()); if (null == sortingAlgorithm) { throw new ArgumentNullException("sortingAlgorithm"); } string[] testItems; using (In inStream = new In(streamName)) { testItems = inStream.ReadAllStrings(); } if (null == testItems) { throw new InternalTestFailureException("No items to test"); } sortingAlgorithm.Sort(testItems); return testItems; }
public void Execute() { // Create sorting algorithm SortingType sortingType = GetSortingType(); if (sortingType == SortingType.Exit) { return; } ISortingAlgorithm algorithm = GetSortingAlgorithm(sortingType); // Get parameters Console.WriteLine("How many runs?"); int runs = ProgramUtils.ReadLineInt(); Console.WriteLine("How many entries per run?"); int amount = ProgramUtils.ReadLineInt(); // Start runs Stopwatch stopWatch = new Stopwatch(); IntegerGenerator generator = new IntegerGenerator(); Console.WriteLine("Sorting..."); long[] results = new long[runs]; for (int i = 0; i < runs; i++) { int[] items = generator.GenerateData(amount, -1_000_000, 1_000_000); stopWatch.Start(); algorithm.Sort(items); stopWatch.Stop(); results[i] = stopWatch.ElapsedMilliseconds; stopWatch.Reset(); Console.Write($"\rProgress: {i+1}/{runs}"); } ProgramUtils.WriteLineImpressive($"The average sorting time of {runs} runs is: {results.Average()} ms"); }
public BaseTestClass(ISortingAlgorithm algorithm) { this.algorithm = algorithm; }
public RhodeLottery(List <int> lotteryNumbers, ISortingAlgorithm sortingAlgorithm) { this.BallSorter = sortingAlgorithm; this.LotteryNumbers = lotteryNumbers; }
public async Task Run(ISortingAlgorithm sortingAlgorithm, IList <int> listToSort, CancellationToken cancellationToken) { IProgress <int> progressBar; IProgress <bool> progressStatusLabel; progressBar = new Progress <int>(value => pbStatus.Value = value); progressStatusLabel = new Progress <bool>(value => lblStatusState.Content = "Sorting..."); lblStatusState.Content = "Pending..."; lblResultSortList.Content = string.Empty; pbStatus.Value = 0; pbStatus.Maximum = listToSort.Count; var task = Task.Factory.StartNew(() => { var stopWatch = new Stopwatch(); stopWatch.Start(); progressStatusLabel.Report(true); var sortedList = sortingAlgorithm.Sort(listToSort, cancellationToken, progressBar); stopWatch.Stop(); return(new SortResult { Duration = stopWatch.Elapsed, SortedList = sortedList }); }); var failed = false; var cancelled = false; var message = string.Empty; var durationOfSort = new TimeSpan(); try { await task; durationOfSort = task.Result.Duration; } catch (OperationCanceledException) { cancelled = true; } catch (Exception ex) { failed = true; message = ex.Message; } if (cancelled) { pbStatus.Value = 0; lblStatusState.Content = "Sort cancelled."; } else if (!failed) { pbStatus.Value = listToSort.Count; lblStatusState.Content = "Done. Time taken: " + durationOfSort; lblResultSortList.Content = String.Join(", ", task.Result.SortedList); } else { lblStatusState.Content = "Sort failed. Message: " + message; } }
public void AddASort(ISortingAlgorithm sort) { listOfSorts.Add(sort); }
private void TestEmptyList(ISortingAlgorithm sort) { IComparable[] a = new IComparable[0]; sort.Sort(ref a); }