public static void PoemReadWrite() { Common_Code.ShowHeader(); // Calls the rest of the Week_2_Class methods PoemReader(); PoemWriter(); }
/// <summary> /// Performs serialized search on pages that contain poem text, returns it in int array /// </summary> /// <returns>Returns a one dimensional int array of the text of the poems</returns> public static int[] GetPoemsInVirtualMemory() { int[] startPoem = Common_Code.GetPoemStartPages(); var count = 0; var temp = new List <int>(); NEXT_POEM: if (count < startPoem.Length) { for (int page = startPoem[count]; page < Common_Code.virtualMemory.GetLength(0); page++) { for (int row = 0; row < Common_Code.virtualMemory.GetLength(1); row++) { for (int col = 0; col < Common_Code.virtualMemory.GetLength(2); col++) { if (Common_Code.virtualMemory[page, row, col] != Common_Code.virtualNull) { temp.Add(Common_Code.virtualMemory[page, row, col]); } else { count++; goto NEXT_POEM; } } } } } return(temp.ToArray()); }
/// <summary> /// Show header, initialize virtualMemory, bubble sort poems by incremented segments and log number of exchanges used by each sort /// </summary> public void BubbleSortAndLog() { // Shows a header in the console similar to the comment at the top of this file Common_Code.ShowHeader(); // Initializes all virtualMemory locations to -99 Common_Code.VirtualMemoryInit(); // Reads all three of the poems (TCOTLB.txt, RC.txt, GEAH.txt) in textDir (C:\devel\TFiles\) Week_2_Class.PoemReader(); // Search virtualMemory for the text of the poems and put it in an array int[] allPoems = GetPoemsInVirtualMemory(); int totalPoemsLength = allPoems.Length; // Variable to track the number of exchanges used in a sort int exchanges; // Sort a segment of allPoems of size 10 exchanges = BubbleSortSegment(allPoems, 10); // Write the log from the size 10 sort WriteEfficiencyLog(10, exchanges, Common_Code.bubbleSort); // Sort and log segments of the array starting at 100 and incrementing by 100 every time (100, 200, 300, etc) up to 2000 for (int i = 100; i <= 2000; i += 100) { exchanges = BubbleSortSegment(allPoems, i); WriteEfficiencyLog(i, exchanges, Common_Code.bubbleSort); } bool keepSorting = Common_Code.YesNo("Keep sorting segments from size 2000 to 5927 (may take a few minutes)"); if (keepSorting) { // Sort and log segments of the array starting at 2000 and incrementing by 100 every time (2000, 2100, 2200, etc) up to 5900 for (int i = 2000; i <= totalPoemsLength; i += 100) { exchanges = BubbleSortSegment(allPoems, i); WriteEfficiencyLog(i, exchanges, Common_Code.bubbleSort); } // Sort the entire array exchanges = BubbleSort(allPoems); // Write the log for the full sort WriteEfficiencyLog(totalPoemsLength, exchanges, Common_Code.bubbleSort); } // Write all locations in the sortable source array to log file for debugging Common_Code.IntArrayLog(allPoems, "AllPoems"); // Write all locations in virtual memory to log file for debugging Common_Code.VirtualMemoryLog(10, true); }
static void Main(string[] args) { Common_Code.ShowHeader(); WeekSelect(); // Calls CenterWrite method and sends it the given string to display centered in console Common_Code.CenterWrite("Press Enter to open the log folder and exit the program..."); Console.ReadLine(); Common_Code.OpenLogFolder(); }
/// <summary> /// Writes a log file with a line of "1" listed for the value in logAmount. /// </summary> /// <param name="segmentSize">The size of the segment that the algorithm was performed on.</param> /// <param name="logAmount">The number of ones to log; a measure of operations that were performed by the algorithm.</param> /// <param name="algorithmType">The type of algorithm that was performed.</param> public static void WriteEfficiencyLog(int segmentSize, int logAmount, string algorithmType) { string logFilePath = Common_Code.GetLogFilePath("Efficiency_" + algorithmType, ("Size" + segmentSize.ToString())); using (var logger = new StreamWriter(logFilePath)) { for (int i = 0; i <= logAmount; i++) { logger.WriteLine(1); } } }
/// <summary> /// Write the given frequency sort array to a log file with the given value appended as "Size". /// </summary> /// <param name="counters">The an array of the count of each value to be written.</param> /// <param name="segmentSize">The size of the original array that was sorted.</param> public static int FrequencySortToFile(int[] counters, int segmentSize) { string path = Common_Code.GetLogFilePath(Common_Code.frequencySort, "SegmentSize" + segmentSize.ToString() + "_Counters" + counters.ToString()); int logCount = 1; using (var writer = new StreamWriter(path)) { for (int i = 0; i < counters.Length; i++) { for (int j = 0; j < counters[i]; j++) { writer.WriteLine(i); logCount++; } } } return(logCount); }
public static void TextToASCIIdec() { Common_Code.ShowHeader(); var textDir = Common_Code.textDir; // Calls TFileSelect method to find what text file they want to use (in this case for conversion) var fileToConv = TFileSelect(); // Appends "ConV" to filename based on chosen file, assigns result to newFile var newFile = "ConV" + fileToConv; // Confirmation of chosen file, option to restart method to choose new file; if they choose no (YesNo method returns false), restarts method Console.WriteLine("The contents of {0} will be read to ASCII decimal values\nValues will output to new file {1}", fileToConv, newFile); if (!Common_Code.YesNo("Is this ok?")) { TextToASCIIdec(); } // Uses StreamReader.Read method to read one character at a time from the text file // Then uses StreamReader.WriteLine method to write ASCII decimal value for each character // Writes to a file with newFile variable as name, in the textDir folder using (var readChar = new StreamReader(textDir + fileToConv)) { var currentChar = readChar.Read(); using (var write = new StreamWriter(textDir + newFile)) { while (currentChar != -1) { write.WriteLine("{0}", currentChar); currentChar = readChar.Read(); } } } // Tells user what it did, asks if they'd like to convert another file // If YesNo method returns true, restarts TextToASCIIdec method Console.WriteLine("Converted {0} to {1}", fileToConv, newFile); if (Common_Code.YesNo("Would you like to convert another file?")) { TextToASCIIdec(); } }
/// <summary> /// Perform a frequency sort on the given array, with the given value being the number of different items in that array /// </summary> /// <param name="toSort">The array to be sorted.</param> /// <param name="counterSize">The number of different values in the array; e.g. ASCII is 0-255, so counterSize = 255.</param> /// <returns>Returns a measure of the operations performed by the sort.</returns> private static int FrequencySortCount(int[] toSort, int counterSize) { int logCount = 0; int[] frequencyCount = new int[counterSize]; Common_Code.Populate(frequencyCount, 0); // Increment the counter at the index of the ASCII value by 1 and increment log count by 1 since we performed an operation for (int i = 0; i < toSort.Length; i++) { frequencyCount[toSort[i]]++; logCount++; } // I think this should work, test and stuff logCount += FrequencySortToFile(frequencyCount, toSort.Length); return(logCount); }
private static string TFileSelect() { var textDir = Common_Code.textDir; // Creates array of file names in textDir string[] textFiles = Directory.GetFiles(textDir); // Removes path from each string in textFiles array, based on textDir string length for (int i = 0; i < textFiles.Length; i++) { textFiles[i] = textFiles[i].Remove(0, textDir.Length); } // Displays filename for each file in textFiles array, numbered 1, 2, 3, etc, by count var count = 0; foreach (string file in textFiles) { count += 1; Console.WriteLine("{0}: {1}", count, file); } // Tests input for valid integer input, based on number of files in the textFiles array (i.e. the number of files in the textDir folder) // Then subtracts 1 from fileInput so the user's input matches array index var fileInput = 0; do { var request = string.Format("Enter text file to use (1 to {0})", textFiles.Length); Common_Code.CenterWrite(request); var input = Console.ReadLine(); int.TryParse(input, out fileInput); } while ((fileInput <= 0) && (fileInput > textFiles.Length)); fileInput -= 1; return(textFiles[fileInput]); }
/// <summary> /// Sorts the values of the array by stepping through it repeatedly and comparing each value to the next. /// Returns the total number of exchanges made by the sort. /// </summary> /// <param name="toSort">The array to be sorted.</param> /// <returns>Total number of exchanges performed by the sort.</returns> public int BubbleSort(int[] toSort, bool log = true) { int totalExchanges = 0; for (int number = toSort.Length - 1; number > 0; number--) { for (int i = 0; i < number; i++) { if ((toSort[i]) > (toSort[i + 1])) { ExchangeValues(toSort, i, (i + 1)); totalExchanges += 3; } } } if (log) { // Write all locations in the sorted array to log for debugging Common_Code.IntArrayLog(toSort, "Size" + toSort.Length.ToString()); } return(totalExchanges); }
/// <summary> /// Reads all three of the poems (TCOTLB.txt, RC.txt, GEAH.txt) in textDir (C:\devel\TFiles\) /// </summary> public static void PoemReader() { string poemOneFilePath = string.Format(Common_Code.textDir + Common_Code.theChargeOfTheLightBrigade); string poemTwoFilePath = string.Format(Common_Code.textDir + Common_Code.richardCory); string poemThreeFilePath = string.Format(Common_Code.textDir + Common_Code.greenEggsAndHam); // Reverse array if it hasn't already been reversed // Order before reverse: GEAH, RC, TCOTLB; After reverse: TCOTLB, RC, GEAH // Since TCOTLB comes at page 10, and GEAH comes at page 400, it makes more sense to me reversed if (textFiles[0] == (poemThreeFilePath)) { Array.Reverse(textFiles); } // Test textFiles array elements to ensure they are the correct poems try { if ((textFiles[0] != poemOneFilePath) || (textFiles[1] != poemTwoFilePath) || (textFiles[2] != poemThreeFilePath)) { Console.WriteLine("{0}", missingFiles); // Calls method to display "Press enter to continue..." prompt Common_Code.DisplayFooter(); PoemReader(); } } // Spit out an error if the files are missing, then restart PoemReader method catch (IndexOutOfRangeException e) { Console.WriteLine("{0}", e); Console.WriteLine("{0}", missingFiles); Common_Code.DisplayFooter(); PoemReader(); } // Creates 3D virtualMemory array and initializes all locations to -99 Common_Code.VirtualMemoryInit(); // Declaring counters int pageCount = 0; int rowCount = 0; int colCount = 0; // Declare an int array so loop can tell at what page to start reading each poem int[] startPoem = Common_Code.GetPoemStartPages(); // Main block for reading poems into memory try { for (int poem = 0; poem <= startPoem.Length;) { using (StreamReader readPoem = new StreamReader(textFiles[poem])) { while (pageCount < maxPage) { // If pageCount is greater than or equal to array element designating appropriate starting page, assign to virtual memory // Also checks if current startPoem value is not nilPage (already read) if ((pageCount >= startPoem[poem]) && (colCount < maxCol) && (rowCount < maxRow) && (startPoem[poem] != nilPage)) { // Assigns to virtualMemory integer array then reads it with (char) cast so they are written as characters var currentChar = readPoem.Read(); if (currentChar != -1) { Common_Code.virtualMemory[pageCount, rowCount, colCount] = currentChar; } // If end of file is reached, set current poem to nilPage to designate it as already read, so it does not get read again // Then, increment poem by 1 and break out of while loop so StreamReader can be set with next poem in textFiles array if (currentChar == -1) { startPoem[poem] = nilPage; ++poem; break; } } // Increments to next element in the array if ((colCount < maxCol) && (rowCount < maxRow)) { ++colCount; } else if (rowCount < maxRow) { ++rowCount; colCount = 0; } else if (rowCount == maxRow) { ++pageCount; rowCount = 0; colCount = 0; } // Increments pageCount if nothing else is possible to get to the next poem else if (pageCount <= startPoem[poem]) { ++pageCount; } } // If poem was incremented so textFiles[poem] would be out of range, break out of for loop if (poem >= textFiles.Length) { break; } } } } // Catch exceptions from above try block and report some probably useful stuff // Shouldn't be possible to reach in normal operation, but useful for debugging! catch (Exception e) { Console.WriteLine("{0}", e); Console.WriteLine("Page: {0}, Row: {1}, Col: {2}", pageCount, rowCount, colCount); Console.WriteLine("virtualMemory.Length: {0}", Common_Code.virtualMemory.Length); } }
public static void PoemWriter() { // Declaring counters int pageCount = 0; int rowCount = 0; int colCount = 0; // Declare an int array so loop can tell at what page to start writing each poem int[] startPoem = new int[] { 9, 29, 399 }; // Main block for writing poems to console try { for (int poem = 0; poem <= startPoem.Length;) { while (pageCount < maxPage) { // If pageCount is greater than or equal to array element designating appropriate starting page, write character to console // Also checks if current startPoem value is not nilPage (already read) if ((pageCount >= startPoem[poem]) && (colCount < maxCol) && (rowCount < maxRow) && (startPoem[poem] != nilPage)) { // Writes virtualMemory integer with (char) cast var currentChar = Common_Code.virtualMemory[pageCount, rowCount, colCount]; if (currentChar != -99) { Console.Write("{0}", (char)currentChar); ++colCount; } // If end of poem was reached, set current poem to nilPage to designate it as already written, so it does not get written again // Then, increment poem by 1 to start writing the next poem in the process else if (currentChar == -99) { startPoem[poem] = nilPage; ++poem; // Breaks out of while loop if necessary if (poem >= startPoem.Length) { break; } } } // Increments as needed else if (colCount < maxCol) { Console.Write(' '); ++colCount; } else if (rowCount < maxRow) { ++rowCount; colCount = 0; } else if (rowCount == maxRow) { ++pageCount; rowCount = 0; colCount = 0; Console.Write("Page {0}", pageCount); Common_Code.DisplayFooter(); } } // Breaks out of for loop if necessary if (poem >= startPoem.Length) { break; } } } // Catch exceptions from above try block and report some probably useful stuff // Shouldn't be possible to reach in normal operation, but useful for debugging! catch (Exception e) { Console.WriteLine("{0}", e); Console.WriteLine("Page: {0}, Row: {1}, Col: {2}", pageCount, rowCount, colCount); Console.WriteLine("virtualMemory.Length: {0}", Common_Code.virtualMemory.Length); } // This is where we end up after the last poem in textFiles array is read // Run through pages with user prompt at each page, until page 500, where program gets sent back to Main(), prompting exit // Seems somewhat redundant but not sure how to write it better, maybe write a method that does this and use it in both places (here and above, in the main poem loop) try { while (pageCount < maxPage) { if (colCount < maxCol) { Console.Write(' '); ++colCount; } else if (rowCount < maxRow) { ++rowCount; colCount = 0; } else if (rowCount == maxRow) { ++pageCount; rowCount = 0; colCount = 0; Console.Write("Page {0}", pageCount); Common_Code.DisplayFooter(); } } } // Catch exceptions from above try block and report some probably useful stuff // Shouldn't be possible to reach in normal operation catch (Exception e) { Console.WriteLine("{0}", e); Console.WriteLine("Page: {0}, Row: {1}, Col: {2}", pageCount, rowCount, colCount); Console.WriteLine("virtualMemory.Length: {0}", Common_Code.virtualMemory.Length); } }
/// <summary> /// Perform sorts (bucket, frequency, bubble) on a page of randomized integers in virtual memory and log their efficiency. /// </summary> public static void SortComparisons() { Common_Code.ShowHeader(); Common_Code.VirtualMemoryInit(); int pageToTwoDBucketSort = 200; int pageToFrequencySort = 205; int pageToBubbleSort = 210; // Use the default 0 and 1,500,000 as min and max to populate the pages with random numbers. // Not counting this towards the logCounter value since it's not part of the sorts being performed. PopulatePage(pageToTwoDBucketSort, minValue, maxValue); PopulatePage(pageToFrequencySort, minValue, maxValue); PopulatePage(pageToBubbleSort, minValue, maxValue); // Increment this value by 1 every time a variable (other than the logCount variable itself) changes. // Includes variable changes in iterators (e.g. for (int i = 0; i < 100; i++) should increase logCount by 1 for each iteration, for a total of 100). // Does not include variable declaration/initialization. int logCount = 0; // FindMinAndMax() Reassigns minValue and maxValue to whatever the lowest and highest numbers that were generated are (respectively). // Tracks how many iterations it takes (17 * 80 = 1360) to find the min and max values so it can be added to logCount. // Also, not every sort uses minValue and maxValue - only Frequency Sort and Bucket Sort, so I'm only increasing logCount by this for those sorts. int findMinAndMax = FindMinAndMax(pageToTwoDBucketSort); #region Sorts #region 2-Dimensional Bucket Sort // Set logCount to findMinAndMax since BucketSort uses them logCount += findMinAndMax; // Get the number of times to log based on operations performed during the bucket sort (i.e. total variable assignments it took to sort). logCount += TwoDBucketSortPage(pageToTwoDBucketSort); Week_10_Class.WriteEfficiencyLog(pageSize, logCount, Common_Code.arrayBucketSort); Console.WriteLine("After bucket sort on page {0}, is it sorted?: {1}", pageToTwoDBucketSort, IsPageSorted(pageToTwoDBucketSort)); Common_Code.DisplayFooter(); #endregion #region Frequency Sort // Reset logCount to findMinAndMax for frequency sort. logCount = findMinAndMax; logCount += FrequencySortPage(pageToFrequencySort); Week_10_Class.WriteEfficiencyLog(pageSize, logCount, Common_Code.frequencySort); Console.WriteLine("After frequency sort on page {0}, is it sorted?: {1}", pageToFrequencySort, IsPageSorted(pageToFrequencySort)); Common_Code.DisplayFooter(); #endregion #region Bubble Sort // Reset logCount to 0 for bubble sort. logCount = 0; // Get number of times to log based on bubble sort operations. logCount += LazyBubbleSortPage(pageToBubbleSort); Week_10_Class.WriteEfficiencyLog(pageSize, logCount, Common_Code.bubbleSort); Console.WriteLine("After bubble sort on page {0}, is it sorted?: {1}", pageToBubbleSort, IsPageSorted(pageToBubbleSort)); Common_Code.DisplayFooter(); #endregion #endregion // Writes locations in virtual memory to a log, excluding -99 (virtualNull), so the sorts can be manually checked for correctness. Common_Code.VirtualMemoryLog(12, false); }
/// <summary> /// Use frequency sort to sort the poems and log the efficiency of the algorithm. /// </summary> public static void FrequencySortAndLog() { // Shows a header in the console similar to the comment at the top of this file Common_Code.ShowHeader(); // Initializes all virtualMemory locations to -99 Common_Code.VirtualMemoryInit(); // Reads all three of the poems (TCOTLB.txt, RC.txt, GEAH.txt) in textDir (C:\devel\TFiles\) Week_2_Class.PoemReader(); // Search virtualMemory for the text of the poems and put it in an array int[] allPoems = Week_10_Class.GetPoemsInVirtualMemory(); // Set log count to total poem array length, since part of this algorithm is loading the poems into the array. int logOneCount = allPoems.Length; // Round the length of allPoems down to nearest 100 // Integer division always rounds down so by dividing by 100 then multiplying by 100 we get the value we want // Examples: // 5927 / 100 = 59.27; C# rounds int to 59; 59 * 100 = 5900 // 5977 / 100 = 59.77; C# rounds int to 59; 59 * 100 = 5900 int poemLengthDownToHundred = allPoems.Length / 100 * 100; // Frequency sort segment of size i // Increase log count by the number of operations performed by a segment sort of size 10 // 255 represents the size of the frequency counters array (i.e. ASCII values 0-255); Parameter exists in case I want to frequency sort things other than ASCII logOneCount += FrequencySortSegment(allPoems, 10, 255); // Write a log file with a 1 for the value of logOneCount Week_10_Class.WriteEfficiencyLog(10, logOneCount, Common_Code.frequencySort); // Repeat above processes for segments of size 100, 200, 300...5900, then size allPoems.Length for (int i = 100; i <= allPoems.Length; i = i < poemLengthDownToHundred ? (i + 100) : allPoems.Length) { // Set log count to total poem array length, since part of this algorithm is loading the poems into the array. logOneCount = allPoems.Length; // Frequency sort a segment of allPoems, segment size: i (100, 200, 300, etc) // Increase log count by the number of operations performed by that sort logOneCount += FrequencySortSegment(allPoems, i, 255); // Write a log file with a 1 for the value of logOneCount Week_10_Class.WriteEfficiencyLog(i, logOneCount, Common_Code.frequencySort); // Break out of loop if i == allPoems.Length, otherwise infinite loop if (i == allPoems.Length) { break; } // Expanded version of above ? : ternary operation (in for() loop iterator) //if (i < poemLengthDownToHundred) //{ // i += 100; //} //else //{ // i = allPoems.Length; //} } // Open the log folder path given in Common_Code.logDir in explorer Common_Code.OpenLogFolder(); }
/// <summary> /// Prompts the user to select which section (week) to run /// </summary> /// <remarks>Week input do-while loop had a bug almost the whole semester where it wasn't actually doing anything because I used && (AND) instead of || (OR). Whoops.</remarks> private static void WeekSelect() { // Tests input for valid integers (1 through 16), asks again if input is invalid var weekInput = 0; do { Common_Code.CenterWrite("Enter class week (1 to 16)"); var input = Console.ReadLine(); int.TryParse(input, out weekInput); } while ((weekInput <= 0) || (weekInput > 16)); var labWeek = string.Format("Week {0} was a lab week. Please choose a different week.", weekInput); var futureWeek = string.Format("We aren't at week {0} yet. Please choose a different week.", weekInput); // Sends user to Week_#_Class.Method based on input, restarts WeekSelect method if incorrect input // Defaults to restarting WeekSelect method switch (weekInput) { case 1: Week_1_Class.TextToASCIIdec(); break; case 2: Week_2_Class.PoemReadWrite(); break; case 3: // Sends user to choose which search method to use // Figure we might implement more searches later on down the line // Can just point back to this case for those weeks Common_Code.ChooseSearch(); break; case 4: Console.WriteLine(labWeek); WeekSelect(); break; case 5: Week_5_Class.FindUppercaseT(); break; case 6: Week_6_Class.VirtualStacks(); break; case 7: goto case 4; case 8: Week_8_Class.VirtualQueue(); break; case 9: goto case 4; case 10: // Create new instance of Week_10_Class and start the BubbleSortAndLog method from that class var week_10 = new Week_10_Class(); week_10.BubbleSortAndLog(); break; case 11: Week_11_Class.FrequencySortAndLog(); break; case 12: goto case 16; case 13: goto case 16; case 14: goto case 16; case 15: goto case 16; case 16: Week_12_Class.SortComparisons(); break; default: Console.WriteLine("Entered {0} week, ended in default case - please select a valid week", weekInput); WeekSelect(); break; } }