public static void MathAndStatsProblems() { PrintHelpers.PrintArray("All Sum Combination", new[] { 5 }, AllSumsCombination.GetAllCombinations(5)); PrintHelpers.PrintArray("All Sum Combination 2", new[] { 4 }, AllSumsCombination.GetAllCombinations(4)); Console.WriteLine("Kth Permutation Recusive"); List <char> input = new List <char> { '1', '2', '3', '4' }; Console.WriteLine("Input: { '1', '2', '3', '4' } "); var sb = new System.Text.StringBuilder(); KthPermutation.Find_kth_permutation_rec(input, 7, sb); Console.WriteLine("Output: " + sb); Console.WriteLine(""); Console.WriteLine("Kth Permutation"); input = new List <char> { '1', '2', '3', '4' }; Console.WriteLine("Input: { '1', '2', '3', '4' } "); sb = new System.Text.StringBuilder(); KthPermutation.Find_kth_permutation_rec(input, 7, sb); Console.WriteLine("Output: " + sb); Console.WriteLine("Kth Permutation 2"); input = new List <char> { '1', '2', '3' }; Console.WriteLine("Input: { '1', '2', '3'} "); sb = new System.Text.StringBuilder(); KthPermutation.Find_kth_permutation_rec(input, 4, sb); Console.WriteLine("Output: " + sb); Console.WriteLine(""); Console.WriteLine("Integer Division"); Console.WriteLine("Input: Dividen: 40; Divisor: 4"); Console.WriteLine("Output: " + IntegerDivision.IntegerDivisionRec(40, 4)); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Integer Division 2"); Console.WriteLine("Input: Dividen: 7; Divisor: 3 "); Console.WriteLine("Output: " + IntegerDivision.IntegerDivisionRec(7, 3)); Console.WriteLine(""); var listInput = new List <int> { 4, 6, 8, 1, 3, 5, 10, 9, 7 }; PrintHelpers.PrintArray("Pythagoras Triplet", listInput, PythagorasTriplet.GetPythagorasTriplets(listInput)); Console.WriteLine(""); Console.WriteLine("Find missing number"); Console.WriteLine("Input: { 4, 6, 8, 1, 3, 5, 10, 9, 7} "); Console.WriteLine("Output: "); Console.Write(FindMissingNumber.Find_missing(listInput)); var subsetInput = new List <int> { 2, 3, 4 }; PrintHelpers.PrintArray("All Subsets", subsetInput, AllSubsets.Get_all_subsets(subsetInput)); PrintHelpers.PrintArray("Permute String", new List <string> { "a", "b", "c" }, PermuteString.Permute_string("abc")); Console.WriteLine(""); Console.WriteLine("Is Valid number"); Console.WriteLine("Input: ++4456.054"); Console.Write("Output: "); Console.Write(NumberValid.IsNumberValid("++4456.054")); Console.WriteLine(""); Console.WriteLine("Is Valid number 2"); Console.WriteLine("Input: -4456.054"); Console.Write("Output: "); Console.Write(NumberValid.IsNumberValid("-4456.054")); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Power of Number"); Console.WriteLine("Input: 3,2"); Console.Write("Output: "); Console.Write(PowerOfNumber.Power(3, 2)); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Square root of Number"); Console.WriteLine("Input: 2.2500"); Console.Write("Output: "); Console.Write(SquareRootOfNumber.GetSquareRoot(2.2500)); Console.WriteLine(""); }
/// <summary>Parses a normal or triple-quoted string whose starting quotes /// have been stripped out. If triple-quote parsing was requested, stops /// parsing at three quote marks; otherwise, stops parsing at a single /// end-quote or newline.</summary> /// <returns>true if parsing stopped at one or three quote marks, or false /// if parsing stopped at the end of the input string or at a newline (in /// a string that is not triple-quoted).</returns> /// <remarks>This method recognizes LES and EC#-style string syntax.</remarks> public static bool UnescapeString(ref UString sourceText, char quoteType, bool isTripleQuoted, Action <int, string> onError, StringBuilder sb, UString indentation = default(UString), bool les3TQIndents = false) { Debug.Assert(quoteType == '"' || quoteType == '\'' || quoteType == '`'); bool fail; for (;;) { if (sourceText.IsEmpty) { return(false); } int i0 = sourceText.InternalStart; if (!isTripleQuoted) { EscapeC category = 0; int c = ParseHelpers.UnescapeChar(ref sourceText, ref category); if ((c == quoteType || c == '\n') && sourceText.InternalStart == i0 + 1) { return(c == quoteType); // end of string } if ((category & EscapeC.Unrecognized) != 0) { // This backslash was ignored by UnescapeChar onError(i0, @"Unrecognized escape sequence '\{0}' in string".Localized(PrintHelpers.EscapeCStyle(sourceText[0, ' '].ToString(), EscapeC.Control))); } else if ((category & EscapeC.HasInvalid6DigitEscape) != 0) { onError(i0, @"Invalid 6-digit \u code treated as 5 digits".Localized()); } sb.AppendCodePoint(c); if ((category & EscapeC.BackslashX) != 0 && c >= 0x80) { DetectUtf8(sb); } else if (c.IsInRange(0xDC00, 0xDFFF)) { RecodeSurrogate(sb); } } else { // Inside triple-quoted string int c; if (sourceText[2, '\0'] == '/') { // Detect escape sequence c = ParseHelpers.UnescapeChar(ref sourceText); if (sourceText.InternalStart > i0 + 1) { G.Verify(sourceText.PopFirst(out fail) == '/'); } } else { c = sourceText.PopFirst(out fail); if (fail) { return(false); } if (c == quoteType) { if (sourceText[0, '\0'] == quoteType && sourceText[1, '\0'] == quoteType) { sourceText = sourceText.Substring(2); // end of string return(true); } } if (c == '\r' || c == '\n') { // To ensure platform independency of source code, CR and // CR-LF become LF. if (c == '\r') { c = '\n'; var copy = sourceText.Clone(); if (sourceText.PopFirst(out fail) != '\n') { sourceText = copy; } } // Inside a triple-quoted string, the indentation following a newline // is ignored, as long as it matches the indentation of the first line. UString src = sourceText, ind = indentation; int sp; while ((sp = src.PopFirst(out fail)) == ind.PopFirst(out fail) && !fail) { sourceText = src; } if (les3TQIndents && fail) { // Allow an additional one tab or three spaces when initial indent matches if (sp == '\t') { sourceText = src; } else if (sp == ' ') { sourceText = src; if (src.PopFirst(out fail) == ' ') { sourceText = src; } if (src.PopFirst(out fail) == ' ') { sourceText = src; } } } } } sb.AppendCodePoint(c); } } }
public void Call() { var customers = _customerRepository.GetAll(); PrintHelpers.ShortPrintCustomers(customers); Console.WriteLine("\n Type customer Id or exit"); var isRead = ReadHelpers.TryReadNumber(out var customerId); if (!isRead) { return; } var customer = customers.First(c => c.Id == customerId); Console.WriteLine("Press enter to skip edit"); Console.WriteLine($"First Name: ({customer.FirstName})"); customer.FirstName = ReadHelpers.TryReadLineIfNotEmpty(out var firstName) ? firstName : customer.FirstName; Console.WriteLine($"Last name: ({customer.LastName})"); customer.LastName = ReadHelpers.TryReadLineIfNotEmpty(out var lastName) ? lastName : customer.LastName; Console.WriteLine($"Oib: ({customer.Oib})"); customer.Oib = ReadHelpers.TryReadLineIfNotEmpty(out var oib) ? oib : customer.Oib; Console.WriteLine($"Driving License: ({customer.DrivingLicenseIdentifier})"); customer.DrivingLicenseIdentifier = ReadHelpers.TryReadLineIfNotEmpty(out var drivingLicenseId) ? drivingLicenseId : customer.DrivingLicenseIdentifier; Console.WriteLine($"Date of birth: ({customer.DateOfBirth.ToShortDateString()})"); customer.DateOfBirth = ReadHelpers.TryReadLineIfNotEmpty(out var dateOfBirthString) ? DateTime.ParseExact(dateOfBirthString, DateConstants.DateFormat, null) : customer.DateOfBirth; var response = _customerRepository.Edit(customer, customerId); if (response == ResponseResultType.Success) { PrintHelpers.PrintCustomer(customer); } if (response == ResponseResultType.NotFound) { Console.WriteLine("Customer not found"); } if (response == ResponseResultType.NoChanges) { Console.WriteLine("No changes applied"); } Console.ReadLine(); Console.Clear(); }
public static void LinkedListProblems() { // Linked List // Reverse a linked list LinkedList <int> linked = new LinkedList <int>(); linked.AddLast(1); linked.AddLast(2); linked.AddLast(3); LinkedList <int> linked2 = new LinkedList <int>(); linked2.AddLast(1); linked2.AddLast(2); linked2.AddLast(3); PrintHelpers.PrintArray("Reverse Linked List", linked2.ToArray(), ReverseLinkedList.Reverse(linked).ToArray()); var customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next.Next = new Node <int> { Value = 3 }; var customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 1 }; customLinked2.Head.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next.Next = new Node <int> { Value = 3 }; PrintHelpers.PrintArray("Reverse a Custom Linked List", customLinked2, new CustomLinkedList <int> { Head = ReverseLinkedList.Reverse(customLinked) }); // Remove duplicates in a linked list linked = new LinkedList <int>(); linked.AddLast(1); linked.AddLast(2); linked.AddLast(2); linked.AddLast(3); linked2 = new LinkedList <int>(); linked2.AddLast(1); linked2.AddLast(2); linked2.AddLast(2); linked2.AddLast(3); PrintHelpers.PrintArray("Remove Duplicates", linked2.ToArray(), RemoveDuplicates.RemoveDuplicate(linked).ToArray()); // Remove duplicates in a Custom linked list customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next.Next = new Node <int> { Value = 3 }; customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 1 }; customLinked2.Head.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next.Next = new Node <int> { Value = 3 }; PrintHelpers.PrintArray("Remove Duplicates Custom Linked List", customLinked2, RemoveDuplicates.RemoveDuplicate(customLinked)); // Remove Node with given key in a linked list PrintHelpers.PrintArray("Remove Node with given key ", linked2.ToArray(), RemoveNodeWithGivenKey.Remove(linked, 2).ToArray()); // Remove Node with given key in a Custom linked list PrintHelpers.PrintArray("Remove Node with given key Custom Linked List", customLinked2, RemoveNodeWithGivenKey.Remove(customLinked, 2)); linked = new LinkedList <int>(); linked.AddLast(1); linked.AddLast(2); linked.AddLast(2); linked.AddLast(3); linked2 = new LinkedList <int>(); linked2.AddLast(1); linked2.AddLast(2); linked2.AddLast(2); linked2.AddLast(3); customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next.Next = new Node <int> { Value = 3 }; customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 1 }; customLinked2.Head.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next.Next = new Node <int> { Value = 3 }; // N from last Node in a linked list PrintHelpers.PrintArray("N from last Node in a linked list", linked2.ToArray(), new LinkedList <int>(new[] { NFromLastNode.GetNodeBasedOnPosition(linked, 2).Value }).ToArray(), "Node: 2"); // N from last Node in a Custom linked list PrintHelpers.PrintArray("N from last Node in a custom linked list", customLinked2, new CustomLinkedList <int> { Head = new Node <int> { Value = NFromLastNode.GetNodeBasedOnPosition(customLinked, 2).Value } }, "Node: 2"); // Swap N Node with Head PrintHelpers.PrintArray("Swap N Node with Head", linked2.ToArray(), SwapNnodeWithHead.SwapBasedOnPosition(linked, 2).ToArray(), "Node: 2"); PrintHelpers.PrintArray("Swap N Node with Head", customLinked2, SwapNnodeWithHead.SwapBasedOnPosition(customLinked, 2), "Node: 2"); // Intersection Point of 2 Linked list //LinkedListNode<int> node = new LinkedListNode<int>(5); //linked = new LinkedList<int>(); //linked.AddLast(1); //linked.AddLast(2); //linked.AddLast(2); //linked.AddLast(node); //linked.AddLast(3); //linked2 = new LinkedList<int>(); //linked2.AddLast(1); //linked2.AddLast(2); //linked2.AddLast(2); //linked2.AddLast(node); //linked2.AddLast(3); var node = new Node <int> { Value = 5 }; customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next.Next = node; customLinked.Head.Next.Next.Next.Next = new Node <int> { Value = 3 }; customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 7 }; customLinked2.Head.Next = new Node <int> { Value = 8 }; customLinked2.Head.Next.Next = new Node <int> { Value = 9 }; customLinked2.Head.Next.Next.Next = node; customLinked2.Head.Next.Next.Next.Next = new Node <int> { Value = 3 }; PrintHelpers.PrintArray("Intersection Point of 2 Linked list in Custom Linked List", new[] { customLinked, customLinked2 }, new CustomLinkedList <int> { Head = new Node <int> { Value = IntersectionPointOfTwoLists.GetIntersectionNode(customLinked, customLinked2).Value } }); //Merge two Sorted Arrays linked = new LinkedList <int>(); linked.AddLast(1); linked.AddLast(4); linked.AddLast(8); linked.AddLast(11); linked2 = new LinkedList <int>(); linked2.AddLast(2); linked2.AddLast(4); linked2.AddLast(5); linked2.AddLast(9); PrintHelpers.PrintArray("Merge Two Sorted Arrays", new [] { linked.ToArray(), linked2.ToArray() }, MergeTwoSortedLinkedList.GetMergedList(linked, linked2).ToArray()); customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 4 }; customLinked.Head.Next.Next = new Node <int> { Value = 8 }; customLinked.Head.Next.Next.Next = new Node <int> { Value = 11 }; customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 2 }; customLinked2.Head.Next = new Node <int> { Value = 4 }; customLinked2.Head.Next.Next = new Node <int> { Value = 5 }; customLinked2.Head.Next.Next.Next = new Node <int> { Value = 9 }; PrintHelpers.PrintArray("Merge Two Sorted Arrays in Custom Linked List", new [] { customLinked, customLinked2 }, MergeTwoSortedLinkedList.GetMergedList(customLinked, customLinked2)); // Rotata a linked list customLinked = new CustomLinkedList <int>(); customLinked.Head = new Node <int> { Value = 1 }; customLinked.Head.Next = new Node <int> { Value = 2 }; customLinked.Head.Next.Next = new Node <int> { Value = 3 }; customLinked.Head.Next.Next.Next = new Node <int> { Value = 4 }; customLinked2 = new CustomLinkedList <int>(); customLinked2.Head = new Node <int> { Value = 1 }; customLinked2.Head.Next = new Node <int> { Value = 2 }; customLinked2.Head.Next.Next = new Node <int> { Value = 3 }; customLinked2.Head.Next.Next.Next = new Node <int> { Value = 4 }; PrintHelpers.PrintArray("Rotate in Custom Linked List", customLinked2, RotateLinkedList.Rotate(customLinked, 2)); }
public static void ArrayProblems() { //Arrays //Binary Search int[] input = { 1, 3, 7, 9, 10, 15, 20 }; PrintHelpers.PrintArray("Binary Search", input, new[] { BinarySearch.GetElementIndex(input, 9) }, "K = 9"); PrintHelpers.PrintArray("Binary Search Recursively", input, new[] { BinarySearch.GetElementIndexRecursively(input, 9) }, "K = 9"); // Maximum Sliding Window input = new int[] { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; var ouput = MaximumSlidingWindow.GetMaximumElementPerWindow(input, 4); PrintHelpers.PrintArray("Maximum Sliding Window", input, ouput, "Window Size = 4"); //Sorted Rotate Array Search input = new int[] { 4, 5, 6, 7, 8, 1, 2, 3 }; PrintHelpers.PrintArray("Sorted Rotate Array", input, new[] { SortedRotatedArray.GetElementIndex(input, 8) }, "K = 8"); //Common elements in sorted Array int[] array1 = { 1, 5, 10, 20, 40, 80 }; int[] array2 = { 6, 7, 20, 80, 100 }; int[] array3 = { 3, 4, 15, 20, 30, 70, 80, 120 }; PrintHelpers.PrintArray("Common elements in sorted Array", new[] { array1, array2, array3 }, CommonElementsInThreeSortedArray.GetCommonElements(array1, array2, array3)); //Rotated Array input = new int[] { 1, 3, 7, 9, 10, 15, 20 }; int[] input2 = { 1, 3, 7, 9, 10, 15, 20 }; PrintHelpers.PrintArray("Rotate Array", input, RotateArray.GetRotateArray(input2, 3), "Pivot = 3"); //First and Last Index input = new int[] { 1, 3, 5, 5, 5, 5, 7, 123, 125 }; PrintHelpers.PrintArray("First and Last Index for input", input, FirstAndLast.FindFirstAndLast(input, 7), "Input = 7"); //Move Zeros to Left input = new int[] { 1, 2, 3, 0, 0, 0, 4, 5 }; input2 = new int[] { 1, 2, 3, 0, 0, 0, 4, 5 }; PrintHelpers.PrintArray("Move Zeros to Left", input2, MoveZeroesToLeft.ShiftZeros(input)); //Buy Sell max Profit input = new int[] { 10, 22, 5, 75, 65, 80 }; PrintHelpers.PrintArray("Buy Sell max Profit", input, BuySellMaxProfit.GetBuySellIndex(input)); //Multiple Buy Sell max Profit input = new int[] { 10, 22, 8, 5, 75, 65, 80 }; PrintHelpers.PrintArray("Multiple Buy Sell max Profit", input, BuySellMaxProfit.GetAllBuySellIndex(input)); //Sum of Two Values input = new int[] { 5, 7, 1, 2, 8, 4, 3 }; PrintHelpers.PrintArray("Sum of Two Values", input, SumOfTwoValues.GetPairs(input, 10), "Sum = 10"); //Merging Intervals var inputList = new List <List <int> >(); inputList.Add(new List <int> { 1, 3 }); inputList.Add(new List <int> { 2, 4 }); inputList.Add(new List <int> { 5, 7 }); inputList.Add(new List <int> { 6, 8 }); var inputList2 = new List <List <int> >(); inputList.Add(new List <int> { 1, 3 }); inputList.Add(new List <int> { 2, 4 }); inputList.Add(new List <int> { 5, 7 }); inputList.Add(new List <int> { 6, 8 }); PrintHelpers.PrintArrays("Merging Intervals", inputList2, MergeIntervals.Merge(inputList)); //Quick Sort input = new int[] { 5, 7, 1, 2, 8, 4, 3 }; input2 = new int[] { 5, 7, 1, 2, 8, 4, 3 }; PrintHelpers.PrintArray("Quick Sort", input2, QuickSort.Sort(input)); //Quick Sort input = new int[] { 5, 7, 1, 2, 8, 4, 3 }; input2 = new int[] { 5, 7, 1, 2, 8, 4, 3 }; PrintHelpers.PrintArray("Merge Sort", input2, MergeSort.Merge(input)); //Sum of Three Values input = new int[] { 5, 7, 1, 2, 8, 4, 3 }; input2 = new int[] { 5, 7, 1, 2, 8, 4, 3 }; PrintHelpers.PrintArray("Sum of Three Values", input2, SumOfThreeValues.SumOfThreeValue(input, 10)); }
public static void MatrixProblems() { var input = new int[3, 4] { { 2, 4, 9, 13 }, { 3, 0, 11, 18 }, { 6, 8, 16, 21 } }; PrintHelpers.PrintMatrix("Make Columns And Rows Zeros", input, x => MakeColumnAndRowZeros.MakeZero(input)); input = new int[3, 4] { { 2, 4, 9, 13 }, { 3, 0, 11, 18 }, { 6, 8, 16, 21 } }; PrintHelpers.PrintMatrix("Search in a matrix", input, x => SearchInMatrix.Search(input, 11)); var points = new List <ClosestMeetingPoint.Point> { new ClosestMeetingPoint.Point(2, 1), new ClosestMeetingPoint.Point(2, 2), new ClosestMeetingPoint.Point(2, 3) }; input = new int[5, 5] { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; PrintHelpers.PrintMatrix("Closest Meeting Point ", input, x => ClosestMeetingPoint.ClosestMeetingPt(points, 5)); input = new int[3, 4] { { 2, 4, 9, 13 }, { 3, 0, 11, 18 }, { 6, 8, 16, 21 } }; PrintHelpers.PrintMatrix("Print Spiral Matrix", input, x => SpiralMatrix.Spiral(input)); input = new int[5, 5] { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; PrintHelpers.PrintMatrix("Island", input, x => IslandCount.NumIslands(input)); var charInput = new Char[4, 4] { { '0', '0', '1', 'S' }, { '0', '1', '1', '0' }, { '0', '1', '1', '0' }, { '0', '0', '1', 'D' } }; PrintHelpers.PrintMatrix("Shortest Distance", charInput, x => ShortestDistanceBetweenTwoPoints.GetShortestDistanceBetweenTwoPoints(charInput)); var boggleInput = new Char[3, 3] { { 'c', 'a', 't' }, { 'r', 'r', 'e' }, { 't', 'o', 'n' } }; var boggleDict = new HashSet <string> { "art", "cat", "cater", "cartoon", "toon", "moon", "not", "apple", "ton" }; PrintHelpers.PrintMatrix("Boggle", boggleInput, x => Boggle.GetAllWords(boggleInput, boggleDict)); input = new int[5, 5] { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; PrintHelpers.PrintMatrix("N Queen Problem", input, x => NQueenProblem.GetNQueens(input.GetLength(0))); input = new int[3, 4] { { 2, 4, 9, 13 }, { 3, 0, 11, 18 }, { 6, 8, 16, 21 } }; PrintHelpers.PrintMatrix("Diagonal Matrix", input, x => DiagonaMatrixTraversal.TraverseMatrix(input)); input = new int[4, 4] { { 0, 1, 0, 0 }, { 1, 1, 1, 0 }, { 0, 1, 0, 0 }, { 1, 1, 0, 0 } }; PrintHelpers.PrintMatrix("Island Perimeter", input, x => IslandPerimeter.GetIslandPerimeter(input)); }
private (Bitmap, string, SizeF) ConvertFont(Font font, int minCh, int maxCh, Padding shave, bool autoShave, bool hexStringOutput, bool clearType, bool json, bool fourBitsPerPixel) { var outputs = new List <(string Char, float Width, List <BigInteger> CharBitmap)>(); SizeF maxSize = new SizeF(); int bmpWidth = Min(Max(maxCh - minCh + 1, 0) * MaxCharWidth, 32000); var bitmap = new Bitmap(bmpWidth, MaxCharHeight); using (var g = Graphics.FromImage(bitmap)) { g.Clear(Color.Black); int left = 0; for (int i = minCh; i <= maxCh; i++) { // Measure and draw character (char)i string c = new string((char)i, 1); g.TextRenderingHint = clearType ? TextRenderingHint.ClearTypeGridFit : fourBitsPerPixel ? TextRenderingHint.AntiAliasGridFit : TextRenderingHint.SingleBitPerPixelGridFit; var size = g.MeasureString(c, font); int fullWidth = (int)Round(size.Width); maxSize = new SizeF(Max(size.Width, maxSize.Width), Max(size.Height, maxSize.Height)); g.DrawString(c, font, Brushes.White, left, 0); // Shave off left and right based on actual pixels if (autoShave) { int shaveLeft, shaveRight; for (shaveLeft = 0; shaveLeft < shave.Left; shaveLeft++) { if (!ColumnIsEmpty(left + shaveLeft)) { break; } } for (shaveRight = 0; shaveRight < shave.Right; shaveRight++) { if (!ColumnIsEmpty(left + fullWidth - 1 - shaveRight)) { break; } } shave.Left = shaveLeft; shave.Right = shaveRight; bool ColumnIsEmpty(int x) { if (x < 0) { return(false); } for (int y = 0; y < size.Height; y++) { Color px = bitmap.GetPixel(x, y); if (((px.R + px.G * 2 + px.B) >> 9) != 0) { return(false); } } return(true); } } // Convert to a list of scanlines in 4-bit grayscale var charBitmap = new List <BigInteger>(); for (int y = 0; y < Round(size.Height); y++) { BigInteger row = 0; for (int x = shave.Left; x < fullWidth - shave.Right; x++) { Color px = bitmap.GetPixel(left + x, y); int fourBitGray = (px.R + px.G * 2 + px.B) >> 6; if (fourBitsPerPixel) { row = (row << 4) + fourBitGray; } else { row = (row << 1) + (fourBitGray >> 3); } } charBitmap.Add(row); } bitmap.SetPixel(left, (int)size.Height, Color.Red); outputs.Add((c, Max(size.Width - (shave.Left + shave.Right), 1), charBitmap)); // Advance render position left += Max(fullWidth - shave.Right, 0); } } // Shave top & bottom long mask = fourBitsPerPixel ? 0x888888888888888 : 0xFFFFFFFFFFFFFFF; for (int y = 0; y < shave.Top; y++) { if (autoShave && outputs.Any(item => (item.CharBitmap[0] & mask) != 0)) { break; } foreach (var item in outputs.Where(it => it.CharBitmap.Count > 0)) { item.CharBitmap.RemoveAt(0); } } for (int y = 0; y < shave.Bottom; y++) { if (autoShave && outputs.Any(item => (item.CharBitmap[item.CharBitmap.Count - 1] & mask) != 0)) { break; } foreach (var item in outputs.Where(it => it.CharBitmap.Count > 0)) { item.CharBitmap.RemoveAt(item.CharBitmap.Count - 1); } } var lines = new List <string>(); if (!json) { foreach (var(ch, width, charBitmap) in outputs) { int intWidth = (int)Round(width); string nums = NumberList(intWidth, charBitmap); lines.Add($"{((int)ch[0]).ToString().PadLeft(3,' ')},{intWidth.ToString().PadLeft(2)} ,{nums}, {ch}"); } } else { lines.Add("["); foreach (var(ch, width, charBitmap) in outputs) { string c = "\"" + PrintHelpers.EscapeCStyle(ch) + "\""; if (lines.Any()) { lines[lines.Count - 1] += ","; } lines.Add(@"{"); int intWidth = (int)Round(width); lines.Add($@" ""char"": {c}, ""floatWidth"": {width}, ""width"": {intWidth}, ""bits"":"); if (hexStringOutput) { lines.Add($@" ""{NumberList(intWidth, charBitmap)}"""); } else { lines.Add($" [ {NumberList(intWidth, charBitmap)} ]"); } lines.Add(@"}"); } lines.Add("]"); } return(bitmap, string.Join("\r\n", lines), maxSize); string NumberList(int intWidth, List <BigInteger> charBitmap) { if (hexStringOutput) { int rowLength = fourBitsPerPixel ? intWidth : (intWidth + 3) >> 2; return(string.Join(",", charBitmap.Select(row => row.ToString("X" + rowLength).Right(rowLength)))); } else { return(string.Join(",", charBitmap)); } } }