Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Towel
https://github.com/zacharypatten/towel
Admin
Throw in the towel.
Tokens:
14,451
Snippets:
40
Trust Score:
8.5
License:
MIT
Update:
1 year ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### GraphSetOmnitree Initialization and Edge Operations (C#) Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates how to initialize a GraphSetOmnitree and add nodes and edges. This graph stores nodes in a hashed set and edges in a 2D omnitree (quadtree), suitable for pathfinding algorithms. ```C# IGraph<int> graph = GraphSetOmnitree.New<int>(); // add nodes graph.Add(0); graph.Add(1); graph.Add(2); graph.Add(3); // add edges graph.Add(0, 1); graph.Add(1, 2); graph.Add(2, 3); graph.Add(0, 3); ``` -------------------------------- ### C# Tree Map Initialization Source: https://github.com/zacharypatten/towel/blob/main/README.md Illustrates the initialization of a generic Tree Map (`ITree<T>`) using the `TreeMap.New` method in C#. ```C# ITree<T> treeMap = TreeMap.New<T>(...); ``` -------------------------------- ### Towel Symbolic Mathematics in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates how to use the `Symbolics` component of the Towel library for symbolic mathematics. This includes parsing mathematical expressions from LINQ expressions or strings, simplifying expressions, and performing variable substitutions. ```cs // Parsing From Linq Expression Expression<Func<double, double>> exp1 = (x) => 2 * (x / 7); Symbolics.Expression symExp1 = Symbolics.Parse(exp1); // Parsing From String Symbolics.Expression symExp2 = Symbolics.Parse("2 * ([x] / 7)"); // Mathematical Simplification Symbolics.Expression simplified = symExp1.Simplify(); // Variable Substitution symExp1.Substitute("x", 5); ``` -------------------------------- ### SkipList Initialization and Basic Operations (C#) Source: https://github.com/zacharypatten/towel/blob/main/README.md Illustrates the creation of a SkipList with a specified number of levels and performing basic operations like adding, checking for containment, and removing elements. Skip lists offer O(log n) average complexity for these operations. ```C# SkipList<int, SFunc<int, int, CompareResult>>? list = SkipList.New<int>(5); // create a list with 5 levels list.Add(60); list.Add(20); list.Add(30); list.Add(40); list.Add(20); list.Add(90); list.Add(80); bool result; result = list.Contains(40); //result = true result = list.Remove(40).Suceess; // result = true result = list.Contains(40); //result = false ``` -------------------------------- ### Generic Addition with Runtime Compilation (C#) Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates a technique for performing generic addition using runtime compilation and expression trees in C#. This approach allows breaking type-safety for numeric operations while maintaining performance by compiling the delegate once. ```C# public static T Addition<T>(T a, T b) { return AdditionImplementation<T>.Function(a, b); } internal static class AdditionImplementation<T> { internal static Func<T, T, T> Function = (T a, T b) => { var A = Expression.Parameter(typeof(T)); var B = Expression.Parameter(typeof(T)); var BODY = Expression.Add(A, B); Function = Expression.Lambda<Func<T, T, T>>(BODY, A, B).Compile(); return Function(a, b); }; } ``` -------------------------------- ### Trie Data Structure Initialization (C#) Source: https://github.com/zacharypatten/towel/blob/main/README.md Shows how to initialize different versions of the Trie data structure. Tries are efficient for storing values with shared partial keys, reducing memory usage, and are not limited to string values. ```C# ITrie<T> trie = TrieLinkedHashLinked.New<T>(); ITrie<T, D> trie = TrieLinkedHashLinked.New<T, D>(); ``` -------------------------------- ### Embed Towel Usage Badge in Readme Source: https://github.com/zacharypatten/towel/blob/main/README.md Provides an HTML snippet to embed a 'Using Towel' badge in a project's README file. This badge links directly to the Towel GitHub repository, allowing users to showcase their use of the library. ```HTML <a href="https://github.com/ZacharyPatten/Towel"><img src="https://github.com/ZacharyPatten/Towel/blob/main/.github/Resources/UsingTowel.svg?raw=true" title="Go To Towel"></a> ``` -------------------------------- ### Omnitree Conceptual Overview and Subdivision Algorithms Source: https://github.com/zacharypatten/towel/blob/main/README.md Explains the conceptual structure of an Omnitree, including its multi-dimensional indexing, subdivision algorithms (median, mean), and depth bounding based on the natural logarithm of item count. It details how the tree organizes data and optimizes lookup performance. ```C# // | | | | -4D +3D -2D -1D: 4 +4D +3D -2D -1D: 12 // --- --- --- --- -4D +3D -2D +1D: 5 +4D +3D -2D +1D: 13 // | | | | -4D +3D +2D -1D: 6 +4D +3D +2D -1D: 14 // | | | | -4D +3D +2D +1D: 7 +4D +3D +2D +1D: 15 // | | | | // | | | | // | | | | // v v v v // -1D -2D -3D -4D // // With a value that is in the (+1D, -2D, -3D, +4D)[Index 9] child: // // +1D +2D +3D +4D // ^ ^ ^ ^ // | | | | // | | | | // O--- | | ---O // | \ | | / | // | \ | | / | // --- \ --- --- / --- // | \ | | / | // | \ | | / | // | ---O-----------O--- | // | | | | // | | | | // v v v v // -1D -2D -3D -4D // By default, the omnitree will sort items along each axis and use the median algorithm to determine // the point of divisions. However, you can override the subdivision algorithm. For numerical values, // the mean algorithm can be used (and is much faster than median). If you know the data set will be // relatively evenly distributed within a sub-space, you can even set the subdivision algorithm to // calculate the subdivision from parent spaces rather than looking at the current contents of the // space. // The depth of the omnitree is bounded by "ln(count)" the natural log of the current count. When adding // and item to the tree, if the number of items in the respective child is greater than ln(count) and // the depth bounding has not been reached, then the child will be subdivided. The goal is to achieve // Ω(ln(count)) runtime complexity when looking up values. ``` -------------------------------- ### C# Console Output with Argument Display Source: https://github.com/zacharypatten/towel/blob/main/README.md This C# code fragment illustrates how to print dynamic content to the console. It uses `Console.WriteLine` to display a string constructed with the `nameof` operator (which gets the name of a variable or type as a string) and the value of a variable 'a'. The accompanying output demonstrates the result of running a .NET application with command-line arguments, showing how 'A' and 'a' might be interpreted and displayed. ```C# Console.WriteLine(nameof(A) + " called"); Console.WriteLine(nameof(a) + ": " + a); ``` ```Bash dotnet run A --a 7 ``` ```text A called a: 7 ``` -------------------------------- ### C# Omnitree Interface Initialization Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates the initialization of `IOmnitreePoints` and `IOmnitreeBounds` interfaces in C#. These interfaces represent multi-dimensional spatial partitioning trees for storing points and bounds, respectively. The initialization includes lambda expressions for extracting dimensional coordinates (A1, A2, A3...) from the stored value (T). ```C# // An Omnitree is a Spacial Partitioning Tree (SPT) that works on an arbitrary number of dimensions. // It stores items sorted along multiple dimensions by dividing spaces into sub-spaces. A 3D // version of an SPT is often called an "Octree" and a 2D version of an SPT is often called a // "Quadtree." There are two versions of the Omnitree: Points and Bounds. The Points version stores // vectors while the Bounds version stores spaces with a minimum and maximum vector. IOmnitreePoints<T, A1, A2, A3...> omnitreePoints = new OmnitreePointsLinked<T, A1, A2, A3...>( (T value, out A1 a1, out A2 a2, out A3 a3...) => { ... }); IOmnitreeBounds<T, A1, A2, A3...> omnitreeBounds = new OmnitreeBoundsLinked<T, A1, A2, A3...>(( T value, out A1 min1, out A1 max1, out A2 min2, out A2 max2, out A3 min3, out A3 max3...) => { ... }); ``` -------------------------------- ### Generic Mathematics and Logic API (C#) Source: https://github.com/zacharypatten/towel/blob/main/README.md Defines the API for generic mathematical and logical operations available in the Towel library. These functions allow performing common operations like comparison, arithmetic, prime checking, and statistical calculations on generic types. ```APIDOC // Logic Fundamentals bool Equate<T>(T a , T b) - Compares two generic values for equality. bool LessThan<T>(T a, T b) - Checks if the first generic value is less than the second. bool GreaterThan<T>(T a, T b) - Checks if the first generic value is greater than the second. CompareResult Compare<T>(T a, T b) - Compares two generic values and returns a CompareResult (e.g., Less, Equal, Greater). // Mathematics Fundamentals T Negation<T>(T a) - Returns the negation of a generic numeric value. T Addition<T>(T a, T b) - Returns the sum of two generic numeric values. T Subtraction<T>(T a, T b) - Returns the difference of two generic numeric values. T Multiplication<T>(T a, T b) - Returns the product of two generic numeric values. T Division<T>(T a, T b) - Returns the quotient of two generic numeric values. T Remainder<T>(T a, T b) - Returns the remainder of a division operation between two generic numeric values. // More Logic bool IsPrime<T>(T a) - Checks if a generic numeric value is a prime number. bool IsEven<T>(T a) - Checks if a generic numeric value is an even number. bool IsOdd<T>(T a) - Checks if a generic numeric value is an odd number. T Minimum<T>(T a, T b) - Returns the smaller of two generic values. T Maximum<T>(T a, T b) - Returns the larger of two generic values. T Clamp<T>(T value, T floor, T ceiling) - Clamps a generic value within a specified range [floor, ceiling]. T AbsoluteValue<T>(T a) - Returns the absolute value of a generic numeric value. bool EqualityLeniency<T>(T a, T b, T leniency) - Checks for equality between two generic values within a given leniency (tolerance). // More Numerics void FactorPrimes<T>(T a, ...) - Factors a generic numeric value into its prime components. T Factorial<T>(T a) - Calculates the factorial of a generic numeric value. T LinearInterpolation<T>(T x, T x0, T x1, T y0, T y1) - Performs linear interpolation between two points (x0, y0) and (x1, y1) for a given x. T LeastCommonMultiple<T>(T a, T b, params T[] c) - Calculates the least common multiple (LCM) of two or more generic numeric values. T GreatestCommonFactor<T>(T a, T b, params T[] c) - Calculates the greatest common factor (GCF) of two or more generic numeric values. LinearRegression2D<T>(..., out T slope, out T y_intercept) - Performs 2D linear regression on a set of data points, returning the slope and y-intercept. // Statistics T Mean<T>(T a, params T[] b) - Calculates the arithmetic mean of a set of generic numeric values. T Median<T>(params T[] values) - Calculates the median of a set of generic numeric values. Heap<Link<T, int>> Mode<T>(T a, params T[] b) - Calculates the mode(s) of a set of generic values. void Range<T>(out T minimum, out T maximum, ...) - Determines the minimum and maximum values within a set of generic values. ``` -------------------------------- ### Towel Matrix Operations in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md Illustrates various matrix operations using the `Matrix<T>` class in C#. This covers matrix initialization, basic arithmetic (negation, addition, subtraction), matrix multiplication, scalar multiplication/division, matrix exponentiation, determinant calculation, minor matrix extraction, echelon forms (REF, RREF), inverse, and Lower-Upper (LU) decomposition. ```cs Matrix<T> M1 = new Matrix<T>(int rows, int columns); Matrix<T> M2 = new Matrix<T>(int rows, int columns); Matrix<T> M3; Vector<T> V2 = new Vector<T>(params T[] vector); Vector<T> V3; T scalar; M3 = -M1; // Negate M3 = M1 + M2; // Add M3 = M1 - M2; // Subtract M3 = M1 * M2; // Multiply V3 = M1 * V2; // Multiply (vector) M3 = M1 * scalar; // Multiply (scalar) M3 = M1 / scalar; // Divide M3 = M1 ^ 3; // Power scalar = M1.Determinent(); // Determinent M3 = M1.Minor(int row, int column); // Minor M3 = M1.Echelon(); // Echelon Form (REF) M3 = M1.ReducedEchelon(); // Reduced Echelon Form (RREF) M3 = M1.Inverse(); // Inverse M1.DecomposeLowerUpper(ref M2, ref M3); // Lower Upper Decomposition bool equal = M1 == M2; // Equal ``` -------------------------------- ### Binary Heap Array Representation and Indexing Source: https://github.com/zacharypatten/towel/blob/main/README.md Illustrates the conceptual mapping of a binary heap into a flattened array, showing how parent-child relationships are derived from array indices. It explains the indexing rules for the root, left child, and right child based on a 1-based indexing scheme for the heap elements within the array. ```Conceptual // / \ / \ / \ / \ // Color Red ---> -7 -1 3 6 10 19 30 51 // // Flattened into an Array // // Root = 1 // Left Child = 2 * Index // Right Child = 2* Index + 1 // __________________________________________________________________________ // |0 |7 |1 |22 |-4 |4 |17 |45 |-7 |-1 |3 |6 |10 |19 |30 |51 |0 |0 |0 ... // ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ``` -------------------------------- ### C# Graph Data Structure Conceptual Definition Source: https://github.com/zacharypatten/towel/blob/main/README.md Provides a conceptual definition of a graph data structure in C#, describing it as a collection of nodes and edges useful for modeling real-world scenarios. ```C# // A graph is a data structure that contains nodes and edges. They are useful // when you need to model real world scenarios. They also are generally used ``` -------------------------------- ### Towel C# Command Line Argument Parsing Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet illustrates how to implement command-line argument parsing using the Towel library. By applying the [Command] attribute to static methods, they can be automatically invoked based on command-line arguments passed to the application's Main method via the HandleArguments utility. ```C# // Just put the [Command] attribute on any method you want to call // from the command line, and call the "HandleArguments" method. using System; using static Towel.CommandLine; public static class Program { public static void Main(string[] args) { HandleArguments(args); } [Command] public static void A(int a) { ``` -------------------------------- ### Towel Statistical Methods API Source: https://github.com/zacharypatten/towel/blob/main/README.md Provides a set of generic statistical calculation methods within the Towel library. These methods allow for computations such as quantiles, geometric mean, variance, standard deviation, and mean deviation on various data types. ```APIDOC T[] Quantiles<T>(int quantiles, ...); T GeometricMean<T>(...); T Variance<T>(...); T StandardDeviation<T>(...); T MeanDeviation<T>(...); ``` -------------------------------- ### C# B-Tree Data Structure Implementation and Usage Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates the usage of a B-Tree data structure in C#, including initialization, adding elements, and removing elements. It also provides conceptual comments on B-tree properties, self-balancing, logarithmic time complexity, and the choice between pre-emptive and non-pre-emptive add/remove strategies, noting this implementation uses pre-emptive methods. ```C# // a B-tree is a self-balancing tree data structure that maintains // sorted data and allows searches, sequential access, insertions, // and deletions in logarithmic time. The B-tree generalizes the // binary search tree, allowing for nodes with more than two children. // There are two ways to Add and Remove elements in a B-Tree // 1) Pre-emptive: Search the tree from top to bottom (for place to add/ // node to delete) and perform fixing of the B-Tree (Splitting // or Merging) in a single pass // 2) Non Pre-emptive: Add/Remove the required node and go up the tree to // fix the tree as needed // // Pre-emptive methods are optimal, especially if the Maximum Degree of // a node is set to an even number. This implementation of B-Tree // uses Pre-emptive modes of Add/Removal methods and therefore the // value of Maximum Degree is mandated to be even // This implementation is taken from Thomas H. Cormen's book "Introduction // to Algorithms, 3rd edition", Chapter 18: B-Trees BTree<int> tree = new BTree<int>(4); tree.Add(20); tree.Add(10); tree.Add(30); tree.Add(50); tree.Add(40); tree.Add(5); tree.Add(15); // // [20] // / \ // / \ // [5, 10, 15] [30, 40, 50] // // All elements added in the BTree, where each node can have a maximum // of 4 children (and therefore, a maximum of 3 elements) bool r1 = tree.TryRemove(50).Success; // r1 = true bool r2 = tree.TryRemove(50).Success; // r2 = false, 50 is no longer in the tree // // [20] // / \ // / \ // [5, 10, 15] [30, 40] int[] array = tree.ToArray(); // array = [5, 10, 15, 20, 30, 40] ``` -------------------------------- ### Towel Vector Operations in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates the usage of the `Vector<T>` class in C# for common vector algebra operations. This includes vector initialization, arithmetic operations (addition, subtraction, multiplication, division by scalar), dot product, cross product, magnitude calculation, normalization, and equality checks. ```cs Vector<T> V1 = new Vector<T>(params T[] vector); Vector<T> V2 = new Vector<T>(params T[] vector); Vector<T> V3; T scalar; V3 = -V1; // Negate V3 = V1 + V2; // Add V3 = V1 - V2; // Subtract V3 = V1 * scalar; // Multiply V3 = V1 / scalar; // Divide scalar = V1.DotProduct(V2); // Dot Product V3 = V1.CrossProduct(V2); // Cross Product V1.Magnitude; // Magnitude V3 = V1.Normalize(); // Normalize bool equal = V1 == V2; // Equal ``` -------------------------------- ### BenchmarkDotNet Environment and Job Configuration Source: https://github.com/zacharypatten/towel/blob/main/Tools/docfx_project/benchmarks/SortBenchmarks.md This snippet details the environment setup and job configuration for the BenchmarkDotNet run. It specifies the BenchmarkDotNet version, operating system, CPU, .NET SDK, and runtime information for both the host and the specific job. ```ini BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1469 (21H2) Intel Core i7-4790K CPU 4.00GHz (Haswell), 1 CPU, 8 logical and 4 physical cores .NET SDK=6.0.200-preview.21617.4 [Host] : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT Job-BVYZER : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT InvocationCount=1 UnrollFactor=1 ``` -------------------------------- ### Initialize a Heap Data Structure in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet demonstrates the initialization of a Heap data structure using the `HeapArray.New<T>()` method in C#. Heaps are typically used for priority queues, maintaining a sorted order through 'sifting up' and 'sifting down' algorithms. The accompanying visualization illustrates how a binary tree heap can be flattened into an array representation. ```csharp // and "sifting down" algorithms to move values vertically through the tree to keep items sorted. IHeap<T> heap = HeapArray.New<T>(); // Visualization: // // Binary Tree // // -7 // / \ // / \ // / \ // / \ // / \ // / \ // / \ // / \ // -4 1 // / \ / \ // / \ / \ // / \ / \ // -1 3 6 4 // / \ / \ / \ / \ // 30 10 17 51 45 22 19 7 // // Flattened into an Array // // Root = 1 // Left Child = 2 * Index // Right Child = 2* Index + 1 // __________________________________________________________________________ // |0 |-7 |-4 |1 |-1 |3 |6 |4 |30 |10 |17 |51 |45 |22 |19 |7 |0 |0 |0 ... // ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ``` -------------------------------- ### Towel Supported Measurement Types API Source: https://github.com/zacharypatten/towel/blob/main/README.md Lists the various measurement types supported by the Towel library, designed to facilitate scientific code by providing type-safe handling of physical quantities. Each type is defined by its fundamental dimensions (e.g., Length, Time, Mass, Angle). ```APIDOC // Acceleration: Length/Time/Time // AngularAcceleration: Angle/Time/Time // Angle: Angle // AngularSpeed: Angle/Time // Area: Length*Length // AreaDensity: Mass/Length/Length // Density: Mass/Length/Length/Length // ElectricCharge: ElectricCharge // ElectricCurrent: ElectricCharge/Time // Energy: Mass*Length*Length/Time/Time // Force: Mass*Length/Time/Time // Length: Length // LinearDensity: Mass/Length // LinearMass: Mass*Length // LinearMassFlow: Mass*Length/Time // Mass: Mass // MassRate: Mass/Time // Power: Mass*Length*Length/Time/Time/Time // Pressure: Mass/Length/Time/Time // Speed: Length/Time // Tempurature: Tempurature // Time: Time // TimeArea: Time*Time // Volume: Length*Length*Length // VolumeRate: Length*Length*Length/Time ``` -------------------------------- ### Towel C# Console Helper Methods Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet showcases various utility methods provided by the Towel library's ConsoleHelper class. These methods simplify common console application tasks such as prompting for user input, retrieving validated input, displaying animated progress, rendering progress bars, handling hidden input, managing interactive menus, and flushing the input buffer. ```C# // Just some helper methods for console applications... // wait for keypress to continue an intercept input ConsoleHelper.PromptPressToContinue(...); // generic method for retrieving validated console input ConsoleHelper.GetInput<T>(...); // animated ellipsis character to show processing ConsoleHelper.AnimatedEllipsis(...); // render progress bar in console ConsoleHelper.ProgressBar(...); // Console.ReadLine() with hidden input characters ConsoleHelper.HiddenReadLine(); // easily manage int-based console menus ConsoleHelper.IntMenu(...); // preventing console input ConsoleHelper.FlushInputBuffer(); ``` -------------------------------- ### C# Type Conversion and Parsing Extension Methods Source: https://github.com/zacharypatten/towel/blob/main/README.md This section includes C# extension methods for converting types to their C# source code definitions, converting decimal numbers to English words and vice-versa, and parsing/converting Roman numerals. These utilities simplify string representations and conversions for specific data formats. ```cs // Type conversion to string definition as appears in C# source code string ConvertToCSharpSourceDefinition(this Type type); // Example: typeof(List<int>) -> "System.Collections.Generic.List<int>" string ToEnglishWords(this decimal @decimal); // Example: 42 -> "Forty-Two" (bool Success, decimal Value) TryParseEnglishWordsToDecimal(string words); // Example: "Forty-Two" -> 42 int TryParseRomanNumeral(string @string); // Example: "XLII" -> 42 int TryToRomanNumeral(int value); // Example: 42 -> "XLII" ``` -------------------------------- ### C# Reflection Extension Methods for XML Documentation Access Source: https://github.com/zacharypatten/towel/blob/main/README.md These C# extension methods provide a convenient way to retrieve XML documentation comments associated with various .NET reflection types, such as Type, FieldInfo, PropertyInfo, EventInfo, ConstructorInfo, MethodInfo, MemberInfo, and ParameterInfo. This allows programmatic access to documentation embedded in assemblies. ```cs // Reflection Extensions To Access XML Documentation string GetDocumentation(this Type type); string GetDocumentation(this FieldInfo fieldInfo); string GetDocumentation(this PropertyInfo propertyInfo); string GetDocumentation(this EventInfo eventInfo); string GetDocumentation(this ConstructorInfo constructorInfo); string GetDocumentation(this MethodInfo methodInfo); string GetDocumentation(this MemberInfo memberInfo); string GetDocumentation(this ParameterInfo parameterInfo); ``` -------------------------------- ### Common Algorithms in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md This section lists various algorithms implemented in C#, including palindrome checks, string interleaving, anagrams, a comprehensive suite of sorting algorithms, binary search, distance calculations (Hamming, Levenshtein), permutations, combinations, graph search algorithms (A*, Dijkstra, BFS), and range combination utilities. Many algorithms support System.Span<T> or System.ReadOnlySpan<T> for performance. ```cs // supports System.Span<T> and any (non ref struct) int-indexed type IsPalindrome<...>(...); // supports System.ReadOnlySpan<T> IsInterleavedRecursive<...>(...); IsInterleavedIterative<...>(...); IsReorderOf<...>(...); // aka "anagrams" // supports System.Span<T> and any (non ref struct) int-indexed type SortShuffle<T>(...); SortBubble<T>(...); SortSelection<T>(...); SortInsertion<T>(...); SortQuick<T>(...); SortMerge<T>(...); SortHeap<T>(...); SortOddEven<T>(...); SortCocktail<T>(...); SortComb<T>(...); SortGnome<T>(...); SortShell<T>(...); SortBogo<T>(...); SortSlow<T>(...); SortCycle<T>(...); SortPancake<T>(...); SortStooge<T>(...); SortTim<T>(...); SortIntro<T>(...); SortCounting<T>(...); // uint-based (non-comparative sort) SortRadix<T>(...); // uint-based (non-comparative sort) SortPidgeonHole<T>(...); // int-based (non-comparative sort) // supports System.ReadOnlySpan<T> and any (non ref struct) int-indexed type SearchBinary<T>(...); // supports System.ReadOnlySpan<T> and any (non ref struct) int-indexed type int HammingDistanceIterative<...>(...); int LevenshteinDistanceRecursive<...>(...); int LevenshteinDistanceIterative<...>(...); // Permutations of sequences // supports System.Span<T> and any (non ref struct) int-indexed type void PermuteRecursive<...>(...); void PermuteIterative<...>(...); // Combinations of sequences void Combinations<...>(...); // Path Finding (Graph Search) // overloads for A*, Dijkstra, and Breadth-First-Search algorithms SearchGraph<...>(...); // Combines ranges without gaps between them IEnumerable<(T A, T B)> CombineRanges<T>(IEnumerable<(T A, T B)> ranges) ``` -------------------------------- ### Towel Measurement Type Usage in C# Source: https://github.com/zacharypatten/towel/blob/main/README.md Demonstrates the use of Towel's measurement types for type-safe scientific calculations in C#. It highlights automatic unit conversion during mathematical operations and the compile-time type safety that prevents mathematically invalid operations, such as adding a length to an angle. ```cs // Towel has measurement types to help write scientific code: Acceleration<T>, Angle<T>, Area<T>, // Density<T>, Length<T>, Mass<T>, Speed<T>, Time<T>, Volume<T>, etc. // Automatic Unit Conversion // When you perform mathematical operations on measurements, any necessary unit conversions will // be automatically performed by the relative measurement type (in this case "Angle<T>"). Angle<double> angle1 = (90d, Degrees); Angle<double> angle2 = (.5d, Turns); Angle<double> result1 = angle1 + angle2; // 270° // Type Safeness // The type safe-ness of the measurement types prevents the miss-use of the measurements. You cannot // add "Length<T>" to "Angle<T>" because that is mathematically invalid (no operator exists). Length<double> length1 = (2d, Yards); object result2 = angle1 + length1; // WILL NOT COMPILE!!! // Simplify The Syntax Even Further // You can use alias to remove the generic type if you want to simplify the syntax even further. ``` -------------------------------- ### C# Heap Data Structure Implementation Source: https://github.com/zacharypatten/towel/blob/main/README.md This C# code snippet introduces the concept of a Heap data structure, described as a binary tree sorted vertically. The core rule of a heap is that no parent can be less than either of its children, maintaining a specific order through 'sifting up' operations. ```cs // A heap is a binary tree that is sorted vertically using comparison methods. This is different // from AVL Trees or Red-Black Trees that keep their contents stored horizontally. The rule // of a heap is that no parent can be less than either of its children. A Heap using "sifting up" ``` -------------------------------- ### Towel C# TagAttribute for Value-Based Attributes Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet demonstrates the use of Towel's TagAttribute, which allows developers to attach constant, value-based attributes to code members without creating custom attribute types. It illustrates how to 'tag' a class with a string value and then retrieve that tag at runtime using reflection. ```C# // With TagAttribute's you can make value-based attributes so // you don't always have to make your own custom attribute types. // Just "tag" a code member with constant values. using System; using Towel; var (Found, Value) = typeof(MyClass).GetTag("My Tag"); Console.WriteLine("My Tag..."); Console.WriteLine("Found: " + Found); Console.WriteLine("Value: " + Value); [Tag("My Tag", "hello world")] public class MyClass { } ``` -------------------------------- ### Towel C# Measurement Types and Conversions Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet demonstrates how to define and use strong-typed measurement units in C# with the Towel library. It covers creating speed measurements, integrating them into generic Vector types, and performing various unit conversions using index operators, static conversion methods, and the general Measurement.Convert utility. ```C# using Speedf = Towel.Measurements.Speed<float>; // at top of file Speedf speed1 = (5, Meters / Seconds); // Vector + Measurements // You can use the measurement types inside Towel Vectors. Vector<Speed<float>> velocity1 = new Vector<Speed<float>>( (1f, Meters / Seconds), (2f, Meters / Seconds), (3f, Meters / Seconds)); Vector<Speedf> velocity2 = new Vector<Speedf>( (1f, Centimeters / Seconds), (2f, Centimeters / Seconds), (3f, Centimeters / Seconds)); Vector<Speed<float>> velocity3 = velocity1 + velocity2; // Manual Unit Conversions // 1. Index Operator On Measurement Type double angle1_inRadians = angle1[Radians]; float speed1_inMilesPerHour = speed1[Miles / Hours]; // 2. Static Conversion Methods double angle3 = Angle<double>.Convert(7d, Radians, // from Degrees); // to double speed2 = Speed<double>.Convert(8d, Meters / Seconds, // from Miles / Hours); // to double force1 = Force<double>.Convert(9d, Kilograms * Meters / Seconds / Seconds, // from Grams * Miles / Hours / Hours); // to double angle4 = Measurement.Convert(10d, Radians, // from Degrees); // to // The unit conversion on the Measurement class // is still compile-time-safe. // Measurement Parsing Speed<float>.TryParse("20.5 Meters / Seconds", out Speed<float> parsedSpeed); Force<decimal>.TryParse(".1234 Kilograms * Meters / Seconds / Seconds", out Force<decimal> parsedForce); ``` -------------------------------- ### Towel C# SLazy and ValueLazy for Optimized Lazy Initialization Source: https://github.com/zacharypatten/towel/blob/main/README.md This snippet introduces Towel's SLazy<T> and ValueLazy<T> types, which offer performance improvements over the standard Lazy<T> for lazy initialization scenarios. SLazy<T> is faster when using default thread safety, while ValueLazy<T> provides even greater speed but requires caution as it can call the factory delegate multiple times if the struct is copied. ```C# // SLazy<T> is a faster Lazy<T> when using the default // LazyThreadSafetyMode.ExecutionAndPublication setting. SLazy<string> slazy = new(() => "hello world"); Console.WriteLine(slazy.IsValueCreated); // False Console.WriteLine(slazy.Value); // hello world Console.WriteLine(slazy.IsValueCreated); // True // ValueLazy<T> is even faster than SLazy<T> but it // is unsafe as it will potentially call the factory // delegate multiple times if the struct is copied. // So please use ValueLazy<T> with caution. // There are various types for supporting no multithread lock, // no exception caching, and publication only locks. ``` -------------------------------- ### Omnitree Dimensionality and Child Indexing Visualizations Source: https://github.com/zacharypatten/towel/blob/main/README.md Explains the relationship between the number of dimensions in an Omnitree and the maximum number of children a node can have (2^N). It provides visual representations and child indexing schemes for 1D, 2D, 3D, and 4D Omnitrees, illustrating how child nodes are spatially organized and indexed based on their position along each dimension. ```Conceptual // The maximum number of children any node can have is 2 ^ N where N is the number // of dimensions of the tree. // // ------------------------------- // | Dimensions | Max # Children | // |============|================| // | 1 | 2 ^ 1 = 2 | // | 2 | 2 ^ 2 = 4 | // | 3 | 2 ^ 3 = 8 | // | 4 | 2 ^ 4 = 16 | // | ... | ... | // ------------------------------- // // Visualizations // // 1 Dimensional: // // -1D |-----------|-----------| +1D Children Indexes: // -1D: 0 // <--- 0 ---> <--- 1 ---> +1D: 1 // // 2 Dimensional: // _____________________ // | | | +2D // | | | ^ // | 2 | 3 | | Children Indexes: // | | | | -2D -1D: 0 // |----------|----------| | -2D +1D: 1 // | | | | +2D -1D: 2 // | | | | +2D +1D: 3 // | 0 | 1 | | // | | | v // |__________|__________| -2D // // -1D <-----------> +1D // // 3 Dimensional: // // +3D _____________________ // 7 / / /| // / / 6 / 7 / | // / /---------/----------/ | Children Indexes: // / / 2 / 3 /| | -3D -2D -1D: 0 // L /_________/__________/ | | -3D -2D +1D: 1 // -3D | | | | /| +2D -3D +2D -1D: 2 // | | | |/ | ^ -3D +2D +1D: 3 // | 2 | 3 | / | | +3D -2D -1D: 4 // | | |/| | | +3D -2D +1D: 5 // |----------|----------| | | | +3D +2D -1D: 6 // | | | | / | +3D +2D +1D: 7 // | | | | / | // | 0 | 1 | |/ | // | | | / v // |__________|__________|/ -2D // // ^ // | // 4 (behind 0) // // -1D <-----------> +1D // // 4 Dimensional: // // +1D +2D +3D +4D Children Indexes: // ^ ^ ^ ^ // | | | | -4D -3D -2D -1D: 0 +4D -3D -2D -1D: 8 // | | | | -4D -3D -2D +1D: 1 +4D -3D -2D +1D: 9 // | | | | -4D -3D +2D -1D: 2 +4D -3D +2D -1D: 10 // | | | | -4D -3D +2D +1D: 3 +4D -3D +2D +1D: 11 ```