From f7d23cb4a6f93f94bfc9933943a2e6d3afb0486c Mon Sep 17 00:00:00 2001 From: Karan Chadha Date: Sat, 6 Sep 2025 23:40:31 +0530 Subject: [PATCH] refactor: migrate to file-scoped namespaces and remove unused global usings --- .../Numeric/AdditionWithoutArithmetic.cs | 3 - .../Numeric/KrishnamurthyNumberChecker.cs | 2 - Algorithms/Other/Geofence.cs | 51 +++-- Algorithms/Other/Geohash.cs | 117 ++++++------ Algorithms/Other/JulianEaster.cs | 1 - Algorithms/Other/Triangulator.cs | 84 ++++----- .../ISimilarityCalculator.cs | 4 - Algorithms/Shufflers/LINQShuffler.cs | 38 ++-- Algorithms/Shufflers/NaiveShuffler.cs | 41 ++-- Algorithms/Shufflers/RecursiveShuffler.cs | 69 ++++--- .../Sorters/Comparison/BasicTimSorter.cs | 176 +++++++++--------- Algorithms/Sorters/Utils/GallopingStrategy.cs | 147 +++++++-------- .../Stack/BalancedParenthesesChecker.cs | 127 +++++++------ Algorithms/Stack/NextGreaterElement.cs | 63 +++---- Algorithms/Stack/ReverseStack.cs | 59 +++--- DataStructures/Cache/LfuCache.cs | 1 - DataStructures/Cache/LruCache.cs | 1 - DataStructures/DisjointSet/DisjointSet.cs | 2 - DataStructures/Hashing/Entry.cs | 5 - .../Hashing/NumberTheory/PrimeNumber.cs | 4 - 20 files changed, 470 insertions(+), 525 deletions(-) diff --git a/Algorithms/Numeric/AdditionWithoutArithmetic.cs b/Algorithms/Numeric/AdditionWithoutArithmetic.cs index 7ec294b7..f85ea52d 100644 --- a/Algorithms/Numeric/AdditionWithoutArithmetic.cs +++ b/Algorithms/Numeric/AdditionWithoutArithmetic.cs @@ -1,6 +1,3 @@ -using System; -using System.Numerics; - namespace Algorithms.Numeric; /// diff --git a/Algorithms/Numeric/KrishnamurthyNumberChecker.cs b/Algorithms/Numeric/KrishnamurthyNumberChecker.cs index c4d245a0..a1e40991 100644 --- a/Algorithms/Numeric/KrishnamurthyNumberChecker.cs +++ b/Algorithms/Numeric/KrishnamurthyNumberChecker.cs @@ -1,5 +1,3 @@ -using System; - namespace Algorithms.Numeric; /// diff --git a/Algorithms/Other/Geofence.cs b/Algorithms/Other/Geofence.cs index 90fb9626..59afab77 100644 --- a/Algorithms/Other/Geofence.cs +++ b/Algorithms/Other/Geofence.cs @@ -1,37 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace Algorithms.Other; -namespace Algorithms.Other +public class Geofence { - public class Geofence - { - public double Latitude { get; set; } + public double Latitude { get; set; } - public double Longitude { get; set; } + public double Longitude { get; set; } - public double RadiusInMeters { get; set; } + public double RadiusInMeters { get; set; } - public Geofence(double latitude, double longitude, double radiusInMeters) - { - Latitude = latitude; - Longitude = longitude; - RadiusInMeters = radiusInMeters; - } + public Geofence(double latitude, double longitude, double radiusInMeters) + { + Latitude = latitude; + Longitude = longitude; + RadiusInMeters = radiusInMeters; + } - /// - /// Checks whether the provided user location (latitude and longitude) is within the geofence boundary. - /// The geofence is defined by a center point (latitude, longitude) and a radius in meters. - /// - /// The latitude of the user's current location. - /// The longitude of the user's current location. - /// Returns true if the user is inside the geofence, otherwise returns false. - public bool IsInside(double userLatitude, double userLongitude) - { - double distance = GeoLocation.CalculateDistanceFromLatLng(Latitude, Longitude, userLatitude, userLongitude); - return distance <= RadiusInMeters; - } + /// + /// Checks whether the provided user location (latitude and longitude) is within the geofence boundary. + /// The geofence is defined by a center point (latitude, longitude) and a radius in meters. + /// + /// The latitude of the user's current location. + /// The longitude of the user's current location. + /// Returns true if the user is inside the geofence, otherwise returns false. + public bool IsInside(double userLatitude, double userLongitude) + { + double distance = GeoLocation.CalculateDistanceFromLatLng(Latitude, Longitude, userLatitude, userLongitude); + return distance <= RadiusInMeters; } } diff --git a/Algorithms/Other/Geohash.cs b/Algorithms/Other/Geohash.cs index 53507f85..bde2a759 100644 --- a/Algorithms/Other/Geohash.cs +++ b/Algorithms/Other/Geohash.cs @@ -1,84 +1,79 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -namespace Algorithms.Other +namespace Algorithms.Other; + +public static class Geohash { - public static class Geohash + private const string Base32Characters = "0123456789bcdefghjkmnpqrstuvwxyz"; // Convert latitude and longitude coordinates into a concise string + private const int GeohashLength = 12; // ± 1.86 cm + + /// + /// Encodes the provided latitude and longitude coordinates into a Geohash string. + /// Geohashing is a method to encode geographic coordinates (latitude, longitude). + /// into a short string of letters and digits. Each character in the resulting Geohash . + /// string adds more precision to the location. The longer the Geohash, the smaller the area. + /// + /// The latitude of the location to encode. It must be a value between -90 and 90. + /// The longitude of the location to encode. It must be a value between -180 and 180. + /// + /// A Geohash string of length 12 representing the location with high precision. + /// A longer Geohash provides higher precision in terms of geographic area. + /// and a 12-character Geohash can be accurate down to around 1.86 cm. + /// + public static string Encode(double latitude, double longitude) { - private const string Base32Characters = "0123456789bcdefghjkmnpqrstuvwxyz"; // Convert latitude and longitude coordinates into a concise string - private const int GeohashLength = 12; // ± 1.86 cm + double[] latitudeRange = new[] { -90.0, 90.0 }; + double[] longitudeRange = new[] { -180.0, 180.0 }; + bool isEncodingLongitude = true; + int currentBit = 0; + int base32Index = 0; + StringBuilder geohashResult = new StringBuilder(); - /// - /// Encodes the provided latitude and longitude coordinates into a Geohash string. - /// Geohashing is a method to encode geographic coordinates (latitude, longitude). - /// into a short string of letters and digits. Each character in the resulting Geohash . - /// string adds more precision to the location. The longer the Geohash, the smaller the area. - /// - /// The latitude of the location to encode. It must be a value between -90 and 90. - /// The longitude of the location to encode. It must be a value between -180 and 180. - /// - /// A Geohash string of length 12 representing the location with high precision. - /// A longer Geohash provides higher precision in terms of geographic area. - /// and a 12-character Geohash can be accurate down to around 1.86 cm. - /// - public static string Encode(double latitude, double longitude) + while (geohashResult.Length < GeohashLength) { - double[] latitudeRange = new[] { -90.0, 90.0 }; - double[] longitudeRange = new[] { -180.0, 180.0 }; - bool isEncodingLongitude = true; - int currentBit = 0; - int base32Index = 0; - StringBuilder geohashResult = new StringBuilder(); + double midpoint; - while (geohashResult.Length < GeohashLength) + if (isEncodingLongitude) { - double midpoint; - - if (isEncodingLongitude) + midpoint = (longitudeRange[0] + longitudeRange[1]) / 2; + if (longitude > midpoint) { - midpoint = (longitudeRange[0] + longitudeRange[1]) / 2; - if (longitude > midpoint) - { - base32Index |= 1 << (4 - currentBit); - longitudeRange[0] = midpoint; - } - else - { - longitudeRange[1] = midpoint; - } + base32Index |= 1 << (4 - currentBit); + longitudeRange[0] = midpoint; } else { - midpoint = (latitudeRange[0] + latitudeRange[1]) / 2; - if (latitude > midpoint) - { - base32Index |= 1 << (4 - currentBit); - latitudeRange[0] = midpoint; - } - else - { - latitudeRange[1] = midpoint; - } + longitudeRange[1] = midpoint; } - - isEncodingLongitude = !isEncodingLongitude; - - if (currentBit < 4) + } + else + { + midpoint = (latitudeRange[0] + latitudeRange[1]) / 2; + if (latitude > midpoint) { - currentBit++; + base32Index |= 1 << (4 - currentBit); + latitudeRange[0] = midpoint; } else { - geohashResult.Append(Base32Characters[base32Index]); - currentBit = 0; - base32Index = 0; + latitudeRange[1] = midpoint; } } - return geohashResult.ToString(); + isEncodingLongitude = !isEncodingLongitude; + + if (currentBit < 4) + { + currentBit++; + } + else + { + geohashResult.Append(Base32Characters[base32Index]); + currentBit = 0; + base32Index = 0; + } } + + return geohashResult.ToString(); } } diff --git a/Algorithms/Other/JulianEaster.cs b/Algorithms/Other/JulianEaster.cs index a8649c26..7785f080 100644 --- a/Algorithms/Other/JulianEaster.cs +++ b/Algorithms/Other/JulianEaster.cs @@ -1,5 +1,4 @@ using System; -using System.Globalization; namespace Algorithms.Other; diff --git a/Algorithms/Other/Triangulator.cs b/Algorithms/Other/Triangulator.cs index a9cd27fc..dc7f9af0 100644 --- a/Algorithms/Other/Triangulator.cs +++ b/Algorithms/Other/Triangulator.cs @@ -1,55 +1,51 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Algorithms.Other +namespace Algorithms.Other; + +public class Triangulator { - public class Triangulator + public (double Latitude, double Longitude) CalculatePosition(List<(double Latitude, double Longitude)> baseLocations, List distances) { - public (double Latitude, double Longitude) CalculatePosition(List<(double Latitude, double Longitude)> baseLocations, List distances) + if (baseLocations.Count < 3 || distances.Count < 3) { - if (baseLocations.Count < 3 || distances.Count < 3) - { - throw new ArgumentException("At least three points and corresponding distances are required."); - } - - // Get the coordinates of the three base stations - double lat1 = baseLocations[0].Latitude; - double lon1 = baseLocations[0].Longitude; - double lat2 = baseLocations[1].Latitude; - double lon2 = baseLocations[1].Longitude; - double lat3 = baseLocations[2].Latitude; - double lon3 = baseLocations[2].Longitude; - - // Convert coordinates to radians - lat1 = ToRadians(lat1); - lon1 = ToRadians(lon1); - lat2 = ToRadians(lat2); - lon2 = ToRadians(lon2); - lat3 = ToRadians(lat3); - lon3 = ToRadians(lon3); - - // Calculate the center point - double centerLat = (lat1 + lat2 + lat3) / 3; - double centerLon = (lon1 + lon2 + lon3) / 3; - - // Convert back to degrees - centerLat = ToDegrees(centerLat); - centerLon = ToDegrees(centerLon); - - return (centerLat, centerLon); + throw new ArgumentException("At least three points and corresponding distances are required."); } - private double ToRadians(double degrees) - { - return degrees * Math.PI / 180; - } + // Get the coordinates of the three base stations + double lat1 = baseLocations[0].Latitude; + double lon1 = baseLocations[0].Longitude; + double lat2 = baseLocations[1].Latitude; + double lon2 = baseLocations[1].Longitude; + double lat3 = baseLocations[2].Latitude; + double lon3 = baseLocations[2].Longitude; + + // Convert coordinates to radians + lat1 = ToRadians(lat1); + lon1 = ToRadians(lon1); + lat2 = ToRadians(lat2); + lon2 = ToRadians(lon2); + lat3 = ToRadians(lat3); + lon3 = ToRadians(lon3); + + // Calculate the center point + double centerLat = (lat1 + lat2 + lat3) / 3; + double centerLon = (lon1 + lon2 + lon3) / 3; + + // Convert back to degrees + centerLat = ToDegrees(centerLat); + centerLon = ToDegrees(centerLon); + + return (centerLat, centerLon); + } - private double ToDegrees(double radians) - { - return radians * 180 / Math.PI; - } + private double ToRadians(double degrees) + { + return degrees * Math.PI / 180; + } + + private double ToDegrees(double radians) + { + return radians * 180 / Math.PI; } } diff --git a/Algorithms/RecommenderSystem/ISimilarityCalculator.cs b/Algorithms/RecommenderSystem/ISimilarityCalculator.cs index e055a3c7..5add6c9d 100644 --- a/Algorithms/RecommenderSystem/ISimilarityCalculator.cs +++ b/Algorithms/RecommenderSystem/ISimilarityCalculator.cs @@ -1,8 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Algorithms.RecommenderSystem { diff --git a/Algorithms/Shufflers/LINQShuffler.cs b/Algorithms/Shufflers/LINQShuffler.cs index a3eb6b39..542c0101 100644 --- a/Algorithms/Shufflers/LINQShuffler.cs +++ b/Algorithms/Shufflers/LINQShuffler.cs @@ -1,30 +1,26 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Algorithms.Shufflers +namespace Algorithms.Shufflers; + +/// +/// LINQ Shuffle is a simple shuffling algorithm, +/// where the elements within a collection are shuffled using +/// LINQ queries and lambda expressions in C#. +/// +/// Type array input. +public class LinqShuffler { /// - /// LINQ Shuffle is a simple shuffling algorithm, - /// where the elements within a collection are shuffled using - /// LINQ queries and lambda expressions in C#. + /// First, it will generate a random value for each element. + /// Next, it will sort the elements based on these generated + /// random numbers using OrderBy. /// - /// Type array input. - public class LinqShuffler + /// Array to shuffle. + /// Random generator seed. Used to repeat the shuffle. + public T[] Shuffle(T[] array, int? seed = null) { - /// - /// First, it will generate a random value for each element. - /// Next, it will sort the elements based on these generated - /// random numbers using OrderBy. - /// - /// Array to shuffle. - /// Random generator seed. Used to repeat the shuffle. - public T[] Shuffle(T[] array, int? seed = null) - { - var random = seed is null ? new Random() : new Random(seed.Value); - return array.OrderBy(x => random.Next()).ToArray(); - } + var random = seed is null ? new Random() : new Random(seed.Value); + return array.OrderBy(x => random.Next()).ToArray(); } } diff --git a/Algorithms/Shufflers/NaiveShuffler.cs b/Algorithms/Shufflers/NaiveShuffler.cs index 94e10d18..c50f56f6 100644 --- a/Algorithms/Shufflers/NaiveShuffler.cs +++ b/Algorithms/Shufflers/NaiveShuffler.cs @@ -1,31 +1,30 @@ using System; -namespace Algorithms.Shufflers +namespace Algorithms.Shufflers; + +/// +/// Naive Shuffle is a simple and incorrect shuffling algorithm +/// that randomly swaps every element with any other element in the array. +/// +/// Type array input. +public class NaiveShuffler : IShuffler { /// - /// Naive Shuffle is a simple and incorrect shuffling algorithm - /// that randomly swaps every element with any other element in the array. + /// First, it loop from 0 to n - 1. + /// Next, it will randomly pick any j in the array. + /// Lastly, it will swap array[i] with array[j]. /// - /// Type array input. - public class NaiveShuffler : IShuffler + /// Array to shuffle. + /// Random generator seed. Used to repeat the shuffle. + public void Shuffle(T[] array, int? seed = null) { - /// - /// First, it loop from 0 to n - 1. - /// Next, it will randomly pick any j in the array. - /// Lastly, it will swap array[i] with array[j]. - /// - /// Array to shuffle. - /// Random generator seed. Used to repeat the shuffle. - public void Shuffle(T[] array, int? seed = null) + var random = seed is null ? new Random() : new Random(seed.Value); + for (int i = 0; i < array.Length; i++) { - var random = seed is null ? new Random() : new Random(seed.Value); - for(int i = 0; i < array.Length; i++) - { - int j = random.Next(array.Length); - T temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } + int j = random.Next(array.Length); + T temp = array[i]; + array[i] = array[j]; + array[j] = temp; } } } diff --git a/Algorithms/Shufflers/RecursiveShuffler.cs b/Algorithms/Shufflers/RecursiveShuffler.cs index 4a367e1b..6ff315ca 100644 --- a/Algorithms/Shufflers/RecursiveShuffler.cs +++ b/Algorithms/Shufflers/RecursiveShuffler.cs @@ -1,46 +1,45 @@ using System; -namespace Algorithms.Shufflers +namespace Algorithms.Shufflers; + +/// +/// Recursive Shuffler is a recursive version of +/// Fisher-Yates shuffle algorithm. This can only be used +/// for educational purposes due to stack depth limits. +/// +/// Type array input. +public class RecursiveShuffler : IShuffler { /// - /// Recursive Shuffler is a recursive version of - /// Fisher-Yates shuffle algorithm. This can only be used - /// for educational purposes due to stack depth limits. + /// This is the public overload method that calls the private overload method. /// - /// Type array input. - public class RecursiveShuffler : IShuffler + /// Array to shuffle. + /// Random generator seed. Used to repeat the shuffle. + public void Shuffle(T[] array, int? seed = null) { - /// - /// This is the public overload method that calls the private overload method. - /// - /// Array to shuffle. - /// Random generator seed. Used to repeat the shuffle. - public void Shuffle(T[] array, int? seed = null) - { - Shuffle(array, array.Length - 1, seed); - } + Shuffle(array, array.Length - 1, seed); + } - /// - /// First, it will check the length of the array on the base case. - /// Next, if there's still items left, it will shuffle the sub-array. - /// Lastly, it will randomly select index from 0 to number of items of the array - /// then swap the elements array[items] and array[index]. - /// - /// Array to shuffle. - /// Number of items in the array. - /// Random generator seed. Used to repeat the shuffle. - private void Shuffle(T[] array, int items, int? seed) + /// + /// First, it will check the length of the array on the base case. + /// Next, if there's still items left, it will shuffle the sub-array. + /// Lastly, it will randomly select index from 0 to number of items of the array + /// then swap the elements array[items] and array[index]. + /// + /// Array to shuffle. + /// Number of items in the array. + /// Random generator seed. Used to repeat the shuffle. + private void Shuffle(T[] array, int items, int? seed) + { + if (items <= 0) { - if (items <= 0) - { - return; - } - - Shuffle(array, items - 1, seed); - var random = seed is null ? new Random() : new Random(seed.Value); - int index = random.Next(items + 1); - (array[items], array[index]) = (array[index], array[items]); - (array[items], array[index]) = (array[index], array[items]); + return; } + + Shuffle(array, items - 1, seed); + var random = seed is null ? new Random() : new Random(seed.Value); + int index = random.Next(items + 1); + (array[items], array[index]) = (array[index], array[items]); + (array[items], array[index]) = (array[index], array[items]); } } diff --git a/Algorithms/Sorters/Comparison/BasicTimSorter.cs b/Algorithms/Sorters/Comparison/BasicTimSorter.cs index 2ca6fb33..c278dcd5 100644 --- a/Algorithms/Sorters/Comparison/BasicTimSorter.cs +++ b/Algorithms/Sorters/Comparison/BasicTimSorter.cs @@ -1,120 +1,118 @@ using System; -using System.Collections; using System.Collections.Generic; -namespace Algorithms.Sorters.Comparison +namespace Algorithms.Sorters.Comparison; + +/// +/// A basic implementation of the TimSort algorithm for sorting arrays. +/// +/// The type of elements in the array. +public class BasicTimSorter { + private readonly int minRuns = 32; + private readonly IComparer comparer; + + /// + /// Initializes a new instance of the class. + /// + /// The comparer to use for comparing elements. + public BasicTimSorter(IComparer comparer) + { + this.comparer = comparer ?? Comparer.Default; + } + /// - /// A basic implementation of the TimSort algorithm for sorting arrays. + /// Sorts the specified array using the TimSort algorithm. /// - /// The type of elements in the array. - public class BasicTimSorter + /// The array to sort. + public void Sort(T[] array) { - private readonly int minRuns = 32; - private readonly IComparer comparer; - - /// - /// Initializes a new instance of the class. - /// - /// The comparer to use for comparing elements. - public BasicTimSorter(IComparer comparer) + var n = array.Length; + + // Step 1: Sort small pieces of the array using Insertion Sort + for (var i = 0; i < n; i += minRuns) { - this.comparer = comparer ?? Comparer.Default; + InsertionSort(array, i, Math.Min(i + minRuns - 1, n - 1)); } - /// - /// Sorts the specified array using the TimSort algorithm. - /// - /// The array to sort. - public void Sort(T[] array) + // Step 2: Merge sorted runs using Merge Sort + for (var size = minRuns; size < n; size *= 2) { - var n = array.Length; - - // Step 1: Sort small pieces of the array using Insertion Sort - for (var i = 0; i < n; i += minRuns) + for (var left = 0; left < n; left += 2 * size) { - InsertionSort(array, i, Math.Min(i + minRuns - 1, n - 1)); - } + var mid = left + size - 1; + var right = Math.Min(left + 2 * size - 1, n - 1); - // Step 2: Merge sorted runs using Merge Sort - for (var size = minRuns; size < n; size *= 2) - { - for (var left = 0; left < n; left += 2 * size) + if (mid < right) { - var mid = left + size - 1; - var right = Math.Min(left + 2 * size - 1, n - 1); - - if (mid < right) - { - Merge(array, left, mid, right); - } + Merge(array, left, mid, right); } } } + } - /// - /// Sorts a portion of the array using the Insertion Sort algorithm. - /// - /// The array to sort. - /// The starting index of the portion to sort. - /// The ending index of the portion to sort. - private void InsertionSort(T[] array, int left, int right) + /// + /// Sorts a portion of the array using the Insertion Sort algorithm. + /// + /// The array to sort. + /// The starting index of the portion to sort. + /// The ending index of the portion to sort. + private void InsertionSort(T[] array, int left, int right) + { + for (var i = left + 1; i <= right; i++) { - for (var i = left + 1; i <= right; i++) - { - var key = array[i]; - var j = i - 1; - - // Move elements of array[0..i-1], that are greater than key, - // to one position ahead of their current position - while (j >= left && comparer.Compare(array[j], key) > 0) - { - array[j + 1] = array[j]; - j--; - } + var key = array[i]; + var j = i - 1; - array[j + 1] = key; + // Move elements of array[0..i-1], that are greater than key, + // to one position ahead of their current position + while (j >= left && comparer.Compare(array[j], key) > 0) + { + array[j + 1] = array[j]; + j--; } + + array[j + 1] = key; } + } - /// - /// Merges two sorted subarrays into a single sorted subarray. - /// - /// The array containing the subarrays to merge. - /// The starting index of the first subarray. - /// The ending index of the first subarray. - /// The ending index of the second subarray. - private void Merge(T[] array, int left, int mid, int right) - { - // Create segments for left and right subarrays - var leftSegment = new ArraySegment(array, left, mid - left + 1); - var rightSegment = new ArraySegment(array, mid + 1, right - mid); + /// + /// Merges two sorted subarrays into a single sorted subarray. + /// + /// The array containing the subarrays to merge. + /// The starting index of the first subarray. + /// The ending index of the first subarray. + /// The ending index of the second subarray. + private void Merge(T[] array, int left, int mid, int right) + { + // Create segments for left and right subarrays + var leftSegment = new ArraySegment(array, left, mid - left + 1); + var rightSegment = new ArraySegment(array, mid + 1, right - mid); - // Convert segments to arrays - var leftArray = leftSegment.ToArray(); - var rightArray = rightSegment.ToArray(); + // Convert segments to arrays + var leftArray = leftSegment.ToArray(); + var rightArray = rightSegment.ToArray(); - var i = 0; - var j = 0; - var k = left; + var i = 0; + var j = 0; + var k = left; - // Merge the two subarrays back into the main array - while (i < leftArray.Length && j < rightArray.Length) - { - array[k++] = comparer.Compare(leftArray[i], rightArray[j]) <= 0 ? leftArray[i++] : rightArray[j++]; - } + // Merge the two subarrays back into the main array + while (i < leftArray.Length && j < rightArray.Length) + { + array[k++] = comparer.Compare(leftArray[i], rightArray[j]) <= 0 ? leftArray[i++] : rightArray[j++]; + } - // Copy remaining elements from leftArray, if any - while (i < leftArray.Length) - { - array[k++] = leftArray[i++]; - } + // Copy remaining elements from leftArray, if any + while (i < leftArray.Length) + { + array[k++] = leftArray[i++]; + } - // Copy remaining elements from rightArray, if any - while (j < rightArray.Length) - { - array[k++] = rightArray[j++]; - } + // Copy remaining elements from rightArray, if any + while (j < rightArray.Length) + { + array[k++] = rightArray[j++]; } } } diff --git a/Algorithms/Sorters/Utils/GallopingStrategy.cs b/Algorithms/Sorters/Utils/GallopingStrategy.cs index 4c4ddc02..05f22272 100644 --- a/Algorithms/Sorters/Utils/GallopingStrategy.cs +++ b/Algorithms/Sorters/Utils/GallopingStrategy.cs @@ -1,106 +1,101 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace Algorithms.Sorters.Utils +namespace Algorithms.Sorters.Utils; + +public static class GallopingStrategy { - public static class GallopingStrategy + public static int GallopLeft(T[] array, T key, int baseIndex, int length, IComparer comparer) { - public static int GallopLeft(T[] array, T key, int baseIndex, int length, IComparer comparer) + if (array.Length == 0) { - if (array.Length == 0) - { - return 0; - } + return 0; + } - var (offset, lastOfs) = comparer.Compare(key, array[baseIndex]) > 0 - ? RightRun(array, key, baseIndex, length, 0, comparer) - : LeftRun(array, key, baseIndex, 0, comparer); + var (offset, lastOfs) = comparer.Compare(key, array[baseIndex]) > 0 + ? RightRun(array, key, baseIndex, length, 0, comparer) + : LeftRun(array, key, baseIndex, 0, comparer); - return FinalOffset(array, key, baseIndex, offset, lastOfs, 1, comparer); - } + return FinalOffset(array, key, baseIndex, offset, lastOfs, 1, comparer); + } - public static int GallopRight(T[] array, T key, int baseIndex, int length, IComparer comparer) + public static int GallopRight(T[] array, T key, int baseIndex, int length, IComparer comparer) + { + if (array.Length == 0) { - if (array.Length == 0) - { - return 0; - } + return 0; + } - var (offset, lastOfs) = comparer.Compare(key, array[baseIndex]) < 0 - ? LeftRun(array, key, baseIndex, length, comparer) - : RightRun(array, key, baseIndex, length, 0, comparer); + var (offset, lastOfs) = comparer.Compare(key, array[baseIndex]) < 0 + ? LeftRun(array, key, baseIndex, length, comparer) + : RightRun(array, key, baseIndex, length, 0, comparer); - return FinalOffset(array, key, baseIndex, offset, lastOfs, 0, comparer); - } + return FinalOffset(array, key, baseIndex, offset, lastOfs, 0, comparer); + } - public static int BoundLeftShift(int shiftable) => (shiftable << 1) < 0 - ? (shiftable << 1) + 1 - : int.MaxValue; + public static int BoundLeftShift(int shiftable) => (shiftable << 1) < 0 + ? (shiftable << 1) + 1 + : int.MaxValue; - private static (int Offset, int LastOfs) LeftRun(T[] array, T key, int baseIndex, int hint, IComparer comparer) + private static (int Offset, int LastOfs) LeftRun(T[] array, T key, int baseIndex, int hint, IComparer comparer) + { + var maxOfs = hint + 1; + var (offset, tmp) = (1, 0); + + while (offset < maxOfs && comparer.Compare(key, array[baseIndex + hint - offset]) < 0) { - var maxOfs = hint + 1; - var (offset, tmp) = (1, 0); + tmp = offset; + offset = BoundLeftShift(offset); + } - while (offset < maxOfs && comparer.Compare(key, array[baseIndex + hint - offset]) < 0) - { - tmp = offset; - offset = BoundLeftShift(offset); - } + if (offset > maxOfs) + { + offset = maxOfs; + } - if (offset > maxOfs) - { - offset = maxOfs; - } + var lastOfs = hint - offset; + offset = hint - tmp; - var lastOfs = hint - offset; - offset = hint - tmp; + return (offset, lastOfs); + } - return (offset, lastOfs); + private static (int Offset, int LastOfs) RightRun(T[] array, T key, int baseIndex, int len, int hint, IComparer comparer) + { + var (offset, lastOfs) = (1, 0); + var maxOfs = len - hint; + while (offset < maxOfs && comparer.Compare(key, array[baseIndex + hint + offset]) > 0) + { + lastOfs = offset; + offset = BoundLeftShift(offset); } - private static (int Offset, int LastOfs) RightRun(T[] array, T key, int baseIndex, int len, int hint, IComparer comparer) + if (offset > maxOfs) { - var (offset, lastOfs) = (1, 0); - var maxOfs = len - hint; - while (offset < maxOfs && comparer.Compare(key, array[baseIndex + hint + offset]) > 0) - { - lastOfs = offset; - offset = BoundLeftShift(offset); - } - - if (offset > maxOfs) - { - offset = maxOfs; - } + offset = maxOfs; + } - offset += hint; - lastOfs += hint; + offset += hint; + lastOfs += hint; - return (offset, lastOfs); - } + return (offset, lastOfs); + } - private static int FinalOffset(T[] array, T key, int baseIndex, int offset, int lastOfs, int lt, IComparer comparer) + private static int FinalOffset(T[] array, T key, int baseIndex, int offset, int lastOfs, int lt, IComparer comparer) + { + lastOfs++; + while (lastOfs < offset) { - lastOfs++; - while (lastOfs < offset) + var m = lastOfs + (int)((uint)(offset - lastOfs) >> 1); + + if (comparer.Compare(key, array[baseIndex + m]) < lt) { - var m = lastOfs + (int)((uint)(offset - lastOfs) >> 1); - - if (comparer.Compare(key, array[baseIndex + m]) < lt) - { - offset = m; - } - else - { - lastOfs = m + 1; - } + offset = m; + } + else + { + lastOfs = m + 1; } - - return offset; } + + return offset; } } diff --git a/Algorithms/Stack/BalancedParenthesesChecker.cs b/Algorithms/Stack/BalancedParenthesesChecker.cs index 2f2b8311..0b889933 100644 --- a/Algorithms/Stack/BalancedParenthesesChecker.cs +++ b/Algorithms/Stack/BalancedParenthesesChecker.cs @@ -1,90 +1,89 @@ using System; using System.Collections.Generic; -namespace Algorithms.Stack +namespace Algorithms.Stack; + +/// +/// It checks if an expression has matching and balanced parentheses. +/// @author Mohit Singh. mohit-gogitter +/// +public class BalancedParenthesesChecker { - /// - /// It checks if an expression has matching and balanced parentheses. - /// @author Mohit Singh. mohit-gogitter - /// - public class BalancedParenthesesChecker - { - private static readonly Dictionary ParenthesesMap = new Dictionary + private static readonly Dictionary ParenthesesMap = new Dictionary { { '(', ')' }, { '{', '}' }, { '[', ']' }, }; - /// - /// Determines if a given string expression containing brackets is balanced. - /// A string is considered balanced if all opening brackets have corresponding closing brackets - /// in the correct order. The supported brackets are '()', '{}', and '[]'. - /// - /// - /// The input string expression containing the brackets to check for balance. - /// - /// - /// true if the brackets in the expression are balanced; otherwise, false. - /// - /// - /// Thrown when the input expression contains invalid characters or is null/empty. - /// Only '(', ')', '{', '}', '[', ']' characters are allowed. - /// - public bool IsBalanced(string expression) + /// + /// Determines if a given string expression containing brackets is balanced. + /// A string is considered balanced if all opening brackets have corresponding closing brackets + /// in the correct order. The supported brackets are '()', '{}', and '[]'. + /// + /// + /// The input string expression containing the brackets to check for balance. + /// + /// + /// true if the brackets in the expression are balanced; otherwise, false. + /// + /// + /// Thrown when the input expression contains invalid characters or is null/empty. + /// Only '(', ')', '{', '}', '[', ']' characters are allowed. + /// + public bool IsBalanced(string expression) + { + if (string.IsNullOrEmpty(expression)) + { + throw new ArgumentException("The input expression cannot be null or empty."); + } + + Stack stack = new Stack(); + foreach (char c in expression) { - if (string.IsNullOrEmpty(expression)) + if (IsOpeningParenthesis(c)) { - throw new ArgumentException("The input expression cannot be null or empty."); + stack.Push(c); } - - Stack stack = new Stack(); - foreach (char c in expression) + else if (IsClosingParenthesis(c)) { - if (IsOpeningParenthesis(c)) - { - stack.Push(c); - } - else if (IsClosingParenthesis(c)) - { - if (!IsBalancedClosing(stack, c)) - { - return false; - } - } - else + if (!IsBalancedClosing(stack, c)) { - throw new ArgumentException($"Invalid character '{c}' found in the expression."); + return false; } } - - return stack.Count == 0; - } - - private static bool IsOpeningParenthesis(char c) - { - return c == '(' || c == '{' || c == '['; + else + { + throw new ArgumentException($"Invalid character '{c}' found in the expression."); + } } - private static bool IsClosingParenthesis(char c) - { - return c == ')' || c == '}' || c == ']'; - } + return stack.Count == 0; + } - private static bool IsBalancedClosing(Stack stack, char close) - { - if (stack.Count == 0) - { - return false; - } + private static bool IsOpeningParenthesis(char c) + { + return c == '(' || c == '{' || c == '['; + } - char open = stack.Pop(); - return IsMatchingPair(open, close); - } + private static bool IsClosingParenthesis(char c) + { + return c == ')' || c == '}' || c == ']'; + } - private static bool IsMatchingPair(char open, char close) + private static bool IsBalancedClosing(Stack stack, char close) + { + if (stack.Count == 0) { - return ParenthesesMap.ContainsKey(open) && ParenthesesMap[open] == close; + return false; } + + char open = stack.Pop(); + return IsMatchingPair(open, close); + } + + private static bool IsMatchingPair(char open, char close) + { + return ParenthesesMap.ContainsKey(open) && ParenthesesMap[open] == close; } } diff --git a/Algorithms/Stack/NextGreaterElement.cs b/Algorithms/Stack/NextGreaterElement.cs index 0e5bbecb..c2d728a7 100644 --- a/Algorithms/Stack/NextGreaterElement.cs +++ b/Algorithms/Stack/NextGreaterElement.cs @@ -1,47 +1,46 @@ using System; using System.Collections.Generic; -namespace Algorithms.Stack +namespace Algorithms.Stack; + +/// +/// For each element in an array, the utility finds the next greater element on the right side using a stack. +/// @author Mohit Singh. mohit-gogitter +/// +public class NextGreaterElement { /// - /// For each element in an array, the utility finds the next greater element on the right side using a stack. - /// @author Mohit Singh. mohit-gogitter + /// Finds the next greater element for each element in the input array. + /// The next greater element for an element x is the first element greater than x to its right. + /// If there is no greater element, -1 is returned for that element. /// - public class NextGreaterElement + /// The array of integers to find the next greater elements for. + /// An array where each index contains the next greater element of the corresponding element in the input array, or -1 if no such element exists. + /// Thrown when the input array is null. + public int[] FindNextGreaterElement(int[] nums) { - /// - /// Finds the next greater element for each element in the input array. - /// The next greater element for an element x is the first element greater than x to its right. - /// If there is no greater element, -1 is returned for that element. - /// - /// The array of integers to find the next greater elements for. - /// An array where each index contains the next greater element of the corresponding element in the input array, or -1 if no such element exists. - /// Thrown when the input array is null. - public int[] FindNextGreaterElement(int[] nums) - { - int[] result = new int[nums.Length]; - Stack stack = new Stack(); + int[] result = new int[nums.Length]; + Stack stack = new Stack(); - // Initialize all elements in the result array to -1 - for (int i = 0; i < nums.Length; i++) - { - result[i] = -1; - } + // Initialize all elements in the result array to -1 + for (int i = 0; i < nums.Length; i++) + { + result[i] = -1; + } - for (int i = 0; i < nums.Length; i++) + for (int i = 0; i < nums.Length; i++) + { + // While the stack is not empty and the current element is greater than the element + // corresponding to the index stored at the top of the stack + while (stack.Count > 0 && nums[i] > nums[stack.Peek()]) { - // While the stack is not empty and the current element is greater than the element - // corresponding to the index stored at the top of the stack - while (stack.Count > 0 && nums[i] > nums[stack.Peek()]) - { - int index = stack.Pop(); - result[index] = nums[i]; // Set the next greater element - } - - stack.Push(i); // Push current index to stack + int index = stack.Pop(); + result[index] = nums[i]; // Set the next greater element } - return result; + stack.Push(i); // Push current index to stack } + + return result; } } diff --git a/Algorithms/Stack/ReverseStack.cs b/Algorithms/Stack/ReverseStack.cs index af2f4e26..081f8aec 100644 --- a/Algorithms/Stack/ReverseStack.cs +++ b/Algorithms/Stack/ReverseStack.cs @@ -1,44 +1,43 @@ using System; using System.Collections.Generic; -namespace Algorithms.Stack +namespace Algorithms.Stack; + +/// +/// Reverses the elements in a stack using recursion. +/// @author Mohit Singh. mohit-gogitter +/// +public class ReverseStack { /// - /// Reverses the elements in a stack using recursion. - /// @author Mohit Singh. mohit-gogitter + /// Recursively reverses the elements of the specified stack. /// - public class ReverseStack + /// The type of elements in the stack. + /// The stack to be reversed. This parameter cannot be null. + /// Thrown when the stack parameter is null. + public void Reverse(Stack stack) { - /// - /// Recursively reverses the elements of the specified stack. - /// - /// The type of elements in the stack. - /// The stack to be reversed. This parameter cannot be null. - /// Thrown when the stack parameter is null. - public void Reverse(Stack stack) + if (stack.Count == 0) { - if (stack.Count == 0) - { - return; - } - - T temp = stack.Pop(); - Reverse(stack); - InsertAtBottom(stack, temp); + return; } - private void InsertAtBottom(Stack stack, T value) + T temp = stack.Pop(); + Reverse(stack); + InsertAtBottom(stack, temp); + } + + private void InsertAtBottom(Stack stack, T value) + { + if (stack.Count == 0) + { + stack.Push(value); + } + else { - if (stack.Count == 0) - { - stack.Push(value); - } - else - { - T temp = stack.Pop(); - InsertAtBottom(stack, value); - stack.Push(temp); - } + T temp = stack.Pop(); + InsertAtBottom(stack, value); + stack.Push(temp); } } } diff --git a/DataStructures/Cache/LfuCache.cs b/DataStructures/Cache/LfuCache.cs index 93f9ffd0..546fcc1b 100644 --- a/DataStructures/Cache/LfuCache.cs +++ b/DataStructures/Cache/LfuCache.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace DataStructures.Cache; diff --git a/DataStructures/Cache/LruCache.cs b/DataStructures/Cache/LruCache.cs index 9bbbbce3..185eaf3a 100644 --- a/DataStructures/Cache/LruCache.cs +++ b/DataStructures/Cache/LruCache.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace DataStructures.Cache; diff --git a/DataStructures/DisjointSet/DisjointSet.cs b/DataStructures/DisjointSet/DisjointSet.cs index 1f7b6618..2b03b134 100644 --- a/DataStructures/DisjointSet/DisjointSet.cs +++ b/DataStructures/DisjointSet/DisjointSet.cs @@ -1,5 +1,3 @@ -using System.Collections; - namespace DataStructures.DisjointSet; /// diff --git a/DataStructures/Hashing/Entry.cs b/DataStructures/Hashing/Entry.cs index e7afe8f4..745e4aa7 100644 --- a/DataStructures/Hashing/Entry.cs +++ b/DataStructures/Hashing/Entry.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using DataStructures.Hashing.NumberTheory; - namespace DataStructures.Hashing; /// diff --git a/DataStructures/Hashing/NumberTheory/PrimeNumber.cs b/DataStructures/Hashing/NumberTheory/PrimeNumber.cs index 3dc55e26..412ff022 100644 --- a/DataStructures/Hashing/NumberTheory/PrimeNumber.cs +++ b/DataStructures/Hashing/NumberTheory/PrimeNumber.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace DataStructures.Hashing.NumberTheory; ///