repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Other { /// <summary> /// Almost all real complex decision-making task is described by more than one criterion. /// Therefore, the methods of multicriteria optimization are important. For a wide range /// of tasks multicriteria optimization, described by some axioms of "reasonable" /// behavior in the process of choosing from a set of possible solutions X, each set of /// selected solutions Sel X should be contained in a set optimal for Pareto. /// </summary> public class ParetoOptimization { /// <summary> /// Performs decision optimizations by using Paretor's optimization algorithm. /// </summary> /// <param name="matrix">Contains a collection of the criterias sets.</param> /// <returns>An optimized collection of the criterias sets.</returns> public List<List<decimal>> Optimize(List<List<decimal>> matrix) { var optimizedMatrix = new List<List<decimal>>(matrix.Select(i => i)); int i = 0; while (i < optimizedMatrix.Count) { for (int j = i + 1; j < optimizedMatrix.Count; j++) { decimal directParwiseDifference = GetMinimalPairwiseDifference(optimizedMatrix[i], optimizedMatrix[j]); decimal indirectParwiseDifference = GetMinimalPairwiseDifference(optimizedMatrix[j], optimizedMatrix[i]); /* * in case all criteria of one set are larger that the criteria of another, this * decision is not optimal and it has to be removed */ if (directParwiseDifference >= 0 || indirectParwiseDifference >= 0) { optimizedMatrix.RemoveAt(directParwiseDifference >= 0 ? j : i); i--; break; } } i++; } return optimizedMatrix; } /// <summary> /// Calculates the smallest difference between criteria of input decisions. /// </summary> /// <param name="arr1">Criterias of the first decision.</param> /// <param name="arr2">Criterias of the second decision.</param> /// <returns>Values that represent the smallest difference between criteria of input decisions.</returns> private decimal GetMinimalPairwiseDifference(List<decimal> arr1, List<decimal> arr2) { decimal min = decimal.MaxValue; if (arr1.Count == arr2.Count) { for (int i = 0; i < arr1.Count; i++) { decimal difference = arr1[i] - arr2[i]; if (min > difference) { min = difference; } } } return min; } } }
76
C-Sharp
TheAlgorithms
C#
using System; using Algorithms.Numeric.GreatestCommonDivisor; namespace Algorithms.Other { /// <summary>Implementation of the Pollard's rho algorithm. /// Algorithm for integer factorization. /// Wiki: https://en.wikipedia.org/wiki/Pollard's_rho_algorithm. /// </summary> public static class PollardsRhoFactorizing { public static int Calculate(int number) { var x = 2; var y = 2; var d = 1; var p = number; var i = 0; var gcd = new BinaryGreatestCommonDivisorFinder(); while (d == 1) { x = Fun_g(x, p); y = Fun_g(Fun_g(y, p), p); d = gcd.FindGcd(Math.Abs(x - y), p); i++; } return d; } private static int Fun_g(int x, int p) { return (x * x + 1) % p; } } }
38
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Other { /// <summary> /// The RGB color model is an additive color model in which red, green, and /// blue light are added together in various ways to reproduce a broad array of /// colors. The name of the model comes from the initials of the three additive /// primary colors, red, green, and blue. Meanwhile, the HSV representation /// models how colors appear under light. In it, colors are represented using /// three components: hue, saturation and (brightness-)value. This class /// provides methods for converting colors from one representation to the other. /// (description adapted from https://en.wikipedia.org/wiki/RGB_color_model and /// https://en.wikipedia.org/wiki/HSL_and_HSV). /// </summary> public static class RgbHsvConversion { /// <summary> /// Conversion from the HSV-representation to the RGB-representation. /// </summary> /// <param name="hue">Hue of the color.</param> /// <param name="saturation">Saturation of the color.</param> /// <param name="value">Brightness-value of the color.</param> /// <returns>The tuple of RGB-components.</returns> public static (byte red, byte green, byte blue) HsvToRgb( double hue, double saturation, double value) { if (hue < 0 || hue > 360) { throw new ArgumentOutOfRangeException(nameof(hue), $"{nameof(hue)} should be between 0 and 360"); } if (saturation < 0 || saturation > 1) { throw new ArgumentOutOfRangeException( nameof(saturation), $"{nameof(saturation)} should be between 0 and 1"); } if (value < 0 || value > 1) { throw new ArgumentOutOfRangeException(nameof(value), $"{nameof(value)} should be between 0 and 1"); } var chroma = value * saturation; var hueSection = hue / 60; var secondLargestComponent = chroma * (1 - Math.Abs(hueSection % 2 - 1)); var matchValue = value - chroma; return GetRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); } /// <summary> /// Conversion from the RGB-representation to the HSV-representation. /// </summary> /// <param name="red">Red-component of the color.</param> /// <param name="green">Green-component of the color.</param> /// <param name="blue">Blue-component of the color.</param> /// <returns>The tuple of HSV-components.</returns> public static (double hue, double saturation, double value) RgbToHsv( byte red, byte green, byte blue) { var dRed = (double)red / 255; var dGreen = (double)green / 255; var dBlue = (double)blue / 255; var value = Math.Max(Math.Max(dRed, dGreen), dBlue); var chroma = value - Math.Min(Math.Min(dRed, dGreen), dBlue); var saturation = value.Equals(0) ? 0 : chroma / value; double hue; if (chroma.Equals(0)) { hue = 0; } else if (value.Equals(dRed)) { hue = 60 * (0 + (dGreen - dBlue) / chroma); } else if (value.Equals(dGreen)) { hue = 60 * (2 + (dBlue - dRed) / chroma); } else { hue = 60 * (4 + (dRed - dGreen) / chroma); } hue = (hue + 360) % 360; return (hue, saturation, value); } private static (byte red, byte green, byte blue) GetRgbBySection( double hueSection, double chroma, double matchValue, double secondLargestComponent) { byte red; byte green; byte blue; if (hueSection >= 0 && hueSection <= 1) { red = ConvertToByte(chroma + matchValue); green = ConvertToByte(secondLargestComponent + matchValue); blue = ConvertToByte(matchValue); } else if (hueSection > 1 && hueSection <= 2) { red = ConvertToByte(secondLargestComponent + matchValue); green = ConvertToByte(chroma + matchValue); blue = ConvertToByte(matchValue); } else if (hueSection > 2 && hueSection <= 3) { red = ConvertToByte(matchValue); green = ConvertToByte(chroma + matchValue); blue = ConvertToByte(secondLargestComponent + matchValue); } else if (hueSection > 3 && hueSection <= 4) { red = ConvertToByte(matchValue); green = ConvertToByte(secondLargestComponent + matchValue); blue = ConvertToByte(chroma + matchValue); } else if (hueSection > 4 && hueSection <= 5) { red = ConvertToByte(secondLargestComponent + matchValue); green = ConvertToByte(matchValue); blue = ConvertToByte(chroma + matchValue); } else { red = ConvertToByte(chroma + matchValue); green = ConvertToByte(matchValue); blue = ConvertToByte(secondLargestComponent + matchValue); } return (red, green, blue); } private static byte ConvertToByte(double input) => (byte)Math.Round(255 * input); } }
150
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; namespace Algorithms.Other { /// <summary> /// Implements the Sieve of Eratosthenes. /// </summary> public class SieveOfEratosthenes { private readonly bool[] primes; /// <summary> /// Initializes a new instance of the <see cref="SieveOfEratosthenes"/> class. /// Uses the Sieve of Eratosthenes to precalculate the primes from 0 up to maximumNumberToCheck. /// Requires enough memory to allocate maximumNumberToCheck bytes. /// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes . /// </summary> /// <param name="maximumNumberToCheck">long which specifies the largest number you wish to know if it is prime.</param> public SieveOfEratosthenes(long maximumNumberToCheck) { primes = new bool[maximumNumberToCheck + 1]; // initialize primes array Array.Fill(this.primes, true, 2, primes.Length - 2); for(long i = 2; i * i <= maximumNumberToCheck; i++) { if (!primes[i]) { continue; } for(long composite = i * i; composite <= maximumNumberToCheck; composite += i) { primes[composite] = false; } } } /// <summary> /// Gets the maximumNumberToCheck the class was instantiated with. /// </summary> public long MaximumNumber => primes.Length - 1; /// <summary> /// Returns a boolean indicating whether the number is prime. /// </summary> /// <param name="numberToCheck">The number you desire to know if it is prime or not.</param> /// <returns>A boolean indicating whether the number is prime or not.</returns> public bool IsPrime(long numberToCheck) => primes[numberToCheck]; /// <summary> /// Returns an IEnumerable of long primes in asending order. /// </summary> /// <returns>Primes in ascending order.</returns> public IEnumerable<long> GetPrimes() { for(long i = 2; i < primes.Length; i++) { if (primes[i]) { yield return i; } } } } }
72
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Other { /// <summary>Implementation of Welford's variance algorithm. /// </summary> public class WelfordsVariance { /// <summary> /// Mean accumulates the mean of the entire dataset, /// m2 aggregates the squared distance from the mean, /// count aggregates the number of samples seen so far. /// </summary> private int count; public double Count => count; private double mean; public double Mean => count > 1 ? mean : double.NaN; private double m2; public double Variance => count > 1 ? m2 / count : double.NaN; public double SampleVariance => count > 1 ? m2 / (count - 1) : double.NaN; public WelfordsVariance() { count = 0; mean = 0; } public WelfordsVariance(double[] values) { count = 0; mean = 0; AddRange(values); } public void AddValue(double newValue) { count++; AddValueToDataset(newValue); } public void AddRange(double[] values) { var length = values.Length; for (var i = 1; i <= length; i++) { count++; AddValueToDataset(values[i - 1]); } } private void AddValueToDataset(double newValue) { var delta1 = newValue - mean; var newMean = mean + delta1 / count; var delta2 = newValue - newMean; m2 += delta1 * delta2; mean = newMean; } } }
73
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; namespace Algorithms.Problems.CoinChange { public static class DynamicCoinChangeSolver { /// <summary> /// Generates an array of changes for current coin. /// For instance, having coin C = 6 and array A = [1,3,4] it returns an array R = [2,3,5]. /// Because, 6 - 4 = 2, 6 - 3 = 3, 6 - 1 = 5. /// </summary> /// <param name="coin">The value of the coin to be exchanged.</param> /// <param name="coins">An array of available coins.</param> /// <returns>Array of changes of current coins by available coins.</returns> public static int[] GenerateSingleCoinChanges(int coin, int[] coins) { ValidateCoin(coin); ValidateCoinsArray(coins); var coinsArrayCopy = new int[coins.Length]; Array.Copy(coins, coinsArrayCopy, coins.Length); Array.Sort(coinsArrayCopy); Array.Reverse(coinsArrayCopy); var list = new List<int>(); foreach (var item in coinsArrayCopy) { if (item > coin) { continue; } var difference = coin - item; list.Add(difference); } var result = list.ToArray(); return result; } /// <summary> /// Given a positive integer N, such as coin. /// Generates a change dictionary for all values [1,N]. /// Used in so-called backward induction in search of the minimum exchange. /// </summary> /// <param name="coin">The value of coin.</param> /// <param name="coins">Array of available coins.</param> /// <returns>Change dictionary for all values [1,N], where N is the coin.</returns> public static Dictionary<int, int[]> GenerateChangesDictionary(int coin, int[] coins) { var dict = new Dictionary<int, int[]>(); var currentCoin = 1; while (currentCoin <= coin) { var changeArray = GenerateSingleCoinChanges(currentCoin, coins); dict[currentCoin] = changeArray; currentCoin++; } return dict; } /// <summary> /// Gets a next coin value, such that changes array contains the minimal change overall possible changes. /// For example, having coin N = 6 and A = [1,3,4] coins array. /// The minimum next coin for 6 will be 3, because changes of 3 by A = [1,3,4] contains 0, the minimal change. /// </summary> /// <param name="coin">Coin to be exchanged.</param> /// <param name="exchanges">Dictionary of exchanges for [1, coin].</param> /// <returns>Index of the next coin with minimal exchange.</returns> public static int GetMinimalNextCoin(int coin, Dictionary<int, int[]> exchanges) { var nextCoin = int.MaxValue; var minChange = int.MaxValue; var coinChanges = exchanges[coin]; foreach (var change in coinChanges) { if (change == 0) { return 0; } var currentChange = exchanges[change]; var min = currentChange.Min(); var minIsLesser = min < minChange; if (minIsLesser) { nextCoin = change; minChange = min; } } return nextCoin; } /// <summary> /// Performs a coin change such that an amount of coins is minimal. /// </summary> /// <param name="coin">The value of coin to be exchanged.</param> /// <param name="coins">An array of available coins.</param> /// <returns>Array of exchanges.</returns> public static int[] MakeCoinChangeDynamic(int coin, int[] coins) { var changesTable = GenerateChangesDictionary(coin, coins); var list = new List<int>(); var currentCoin = coin; var nextCoin = int.MaxValue; while (nextCoin != 0) { nextCoin = GetMinimalNextCoin(currentCoin, changesTable); var difference = currentCoin - nextCoin; list.Add(difference); currentCoin = nextCoin; } var result = list.ToArray(); return result; } private static void ValidateCoin(int coin) { if (coin <= 0) { throw new InvalidOperationException($"The coin cannot be lesser or equal to zero {nameof(coin)}."); } } private static void ValidateCoinsArray(int[] coinsArray) { var coinsAsArray = coinsArray.ToArray(); if (coinsAsArray.Length == 0) { throw new InvalidOperationException($"Coins array cannot be empty {nameof(coinsAsArray)}."); } var coinsContainOne = coinsAsArray.Any(x => x == 1); if (!coinsContainOne) { throw new InvalidOperationException($"Coins array must contain coin 1 {nameof(coinsAsArray)}."); } var containsNonPositive = coinsAsArray.Any(x => x <= 0); if (containsNonPositive) { throw new InvalidOperationException( $"{nameof(coinsAsArray)} cannot contain numbers less than or equal to zero"); } var containsDuplicates = coinsAsArray.GroupBy(x => x).Any(g => g.Count() > 1); if (containsDuplicates) { throw new InvalidOperationException($"Coins array cannot contain duplicates {nameof(coinsAsArray)}."); } } } }
175
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Problems.NQueens { public class BacktrackingNQueensSolver { /// <summary> /// Solves N-Queen Problem given a n dimension chessboard and using backtracking with recursion algorithm. /// If we find a dead-end within or current solution we go back and try another position for queen. /// </summary> /// <param name="n">Number of rows.</param> /// <returns>All solutions.</returns> public IEnumerable<bool[,]> BacktrackSolve(int n) { if (n < 0) { throw new ArgumentException(nameof(n)); } return BacktrackSolve(new bool[n, n], 0); } private static IEnumerable<bool[,]> BacktrackSolve(bool[,] board, int col) { var solutions = col < board.GetLength(0) - 1 ? HandleIntermediateColumn(board, col) : HandleLastColumn(board); return solutions; } private static IEnumerable<bool[,]> HandleIntermediateColumn(bool[,] board, int col) { // To start placing queens on possible spaces within the board. for (var i = 0; i < board.GetLength(0); i++) { if (CanPlace(board, i, col)) { board[i, col] = true; foreach (var solution in BacktrackSolve(board, col + 1)) { yield return solution; } board[i, col] = false; } } } private static IEnumerable<bool[,]> HandleLastColumn(bool[,] board) { var n = board.GetLength(0); for (var i = 0; i < n; i++) { if (CanPlace(board, i, n - 1)) { board[i, n - 1] = true; yield return (bool[,])board.Clone(); board[i, n - 1] = false; } } } /// <summary> /// Checks whether current queen can be placed in current position, /// outside attacking range of another queen. /// </summary> /// <param name="board">Source board.</param> /// <param name="row">Row coordinate.</param> /// <param name="col">Col coordinate.</param> /// <returns>true if queen can be placed in given chessboard coordinates; false otherwise.</returns> private static bool CanPlace(bool[,] board, int row, int col) { // To check whether there are any queens on current row. for (var i = 0; i < col; i++) { if (board[row, i]) { return false; } } // To check diagonal attack top-left range. for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i, j]) { return false; } } // To check diagonal attack bottom-left range. for (int i = row + 1, j = col - 1; j >= 0 && i < board.GetLength(0); i++, j--) { if (board[i, j]) { return false; } } // Return true if it can use position. return true; } } }
109
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Problems.StableMarriage { public class Accepter { public Proposer? EngagedTo { get; set; } public List<Proposer> PreferenceOrder { get; set; } = new(); public bool PrefersOverCurrent(Proposer newProposer) => EngagedTo is null || PreferenceOrder.IndexOf(newProposer) < PreferenceOrder.IndexOf(EngagedTo); } }
16
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; namespace Algorithms.Problems.StableMarriage { public static class GaleShapley { /// <summary> /// Finds a stable matching between two equal sets of elements (fills EngagedTo properties). /// time complexity: O(n^2), where n - array size. /// Guarantees: /// - Everyone is matched /// - Matches are stable (there is no better accepter, for any given proposer, which would accept a new match). /// Presented and proven by David Gale and Lloyd Shapley in 1962. /// </summary> public static void Match(Proposer[] proposers, Accepter[] accepters) { if (proposers.Length != accepters.Length) { throw new ArgumentException("Collections must have equal count"); } while (proposers.Any(m => !IsEngaged(m))) { DoSingleMatchingRound(proposers.Where(m => !IsEngaged(m))); } } private static bool IsEngaged(Proposer proposer) => proposer.EngagedTo is not null; private static void DoSingleMatchingRound(IEnumerable<Proposer> proposers) { foreach (var newProposer in proposers) { var accepter = newProposer.PreferenceOrder.First!.Value; if (accepter.EngagedTo is null) { Engage(newProposer, accepter); } else { if (accepter.PrefersOverCurrent(newProposer)) { Free(accepter.EngagedTo); Engage(newProposer, accepter); } } newProposer.PreferenceOrder.RemoveFirst(); } } private static void Free(Proposer proposer) { proposer.EngagedTo = null; } private static void Engage(Proposer proposer, Accepter accepter) { proposer.EngagedTo = accepter; accepter.EngagedTo = proposer; } } }
67
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Problems.StableMarriage { public class Proposer { public Accepter? EngagedTo { get; set; } public LinkedList<Accepter> PreferenceOrder { get; set; } = new(); } }
12
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search { /// <summary> /// Binary Searcher checks an array for element specified by checking /// if element is greater or less than the half being checked. /// time complexity: O(log(n)), /// space complexity: O(1). /// Note: Array must be sorted beforehand. /// </summary> /// <typeparam name="T">Type of element stored inside array. 2.</typeparam> public class BinarySearcher<T> where T : IComparable<T> { /// <summary> /// Finds index of an array by using binary search. /// </summary> /// <param name="sortedData">Sorted array to search in.</param> /// <param name="item">Item to search for.</param> /// <returns>Index of item that equals to item searched for or -1 if none found.</returns> public int FindIndex(T[] sortedData, T item) { var leftIndex = 0; var rightIndex = sortedData.Length - 1; while (leftIndex <= rightIndex) { var middleIndex = leftIndex + (rightIndex - leftIndex) / 2; if (item.CompareTo(sortedData[middleIndex]) > 0) { leftIndex = middleIndex + 1; continue; } if (item.CompareTo(sortedData[middleIndex]) < 0) { rightIndex = middleIndex - 1; continue; } return middleIndex; } return -1; } } }
49
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; namespace Algorithms.Search { /// <summary> /// A Boyer-Moore majority finder algorithm implementation. /// </summary> /// <typeparam name="T">Type of element stored inside array.</typeparam> public static class BoyerMoore<T> where T : IComparable { public static T? FindMajority(IEnumerable<T> input) { var candidate = FindMajorityCandidate(input, input.Count()); if (VerifyMajority(input, input.Count(), candidate)) { return candidate; } return default(T?); } // Find majority candidate private static T FindMajorityCandidate(IEnumerable<T> input, int length) { int count = 1; T candidate = input.First(); foreach (var element in input.Skip(1)) { if (candidate.Equals(element)) { count++; } else { count--; } if (count == 0) { candidate = element; count = 1; } } return candidate; } // Verify that candidate is indeed the majority private static bool VerifyMajority(IEnumerable<T> input, int size, T candidate) { return input.Count(x => x.Equals(candidate)) > size / 2; } } }
59
C-Sharp
TheAlgorithms
C#
using System; using Utilities.Exceptions; namespace Algorithms.Search { /// <summary> /// The idea: you could combine the advantages from both binary-search and interpolation search algorithm. /// Time complexity: /// worst case: Item couldn't be found: O(log n), /// average case: O(log log n), /// best case: O(1). /// Note: This algorithm is recursive and the array has to be sorted beforehand. /// </summary> public class FastSearcher { /// <summary> /// Finds index of first item in array that satisfies specified term /// throws ItemNotFoundException if the item couldn't be found. /// </summary> /// <param name="array">Span of sorted numbers which will be used to find the item.</param> /// <param name="item">Term to check against.</param> /// <returns>Index of first item that satisfies term.</returns> /// <exception cref="ItemNotFoundException"> Gets thrown when the given item couldn't be found in the array.</exception> public int FindIndex(Span<int> array, int item) { if (array.Length == 0) { throw new ItemNotFoundException(); } if (item < array[0] || item > array[^1]) { throw new ItemNotFoundException(); } if (array[0] == array[^1]) { return item == array[0] ? 0 : throw new ItemNotFoundException(); } var (left, right) = ComputeIndices(array, item); var (from, to) = SelectSegment(array, left, right, item); return from + FindIndex(array.Slice(from, to - from + 1), item); } private (int left, int right) ComputeIndices(Span<int> array, int item) { var indexBinary = array.Length / 2; int[] section = { array.Length - 1, item - array[0], array[^1] - array[0], }; var indexInterpolation = section[0] * section[1] / section[2]; // Left is min and right is max of the indices return indexInterpolation > indexBinary ? (indexBinary, indexInterpolation) : (indexInterpolation, indexBinary); } private (int from, int to) SelectSegment(Span<int> array, int left, int right, int item) { if (item < array[left]) { return (0, left - 1); } if (item < array[right]) { return (left, right - 1); } return (right, array.Length - 1); } } }
81
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search { /// <summary> /// Class that implements Fibonacci search algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class FibonacciSearcher<T> where T : IComparable<T> { /// <summary> /// Finds the index of the item searched for in the array. /// Time complexity: /// worst-case: O(log n), /// average-case: O(log n), /// best-case: O(1). /// </summary> /// <param name="array">Sorted array to be searched in. Cannot be null.</param> /// <param name="item">Item to be searched for. Cannot be null.</param> /// <returns>If an item is found, return index. If the array is empty or an item is not found, return -1.</returns> /// <exception cref="ArgumentNullException">Gets thrown when the given array or item is null.</exception> public int FindIndex(T[] array, T item) { if (array is null) { throw new ArgumentNullException("array"); } if (item is null) { throw new ArgumentNullException("item"); } var arrayLength = array.Length; if (arrayLength > 0) { // find the smallest Fibonacci number that equals or is greater than the array length var fibonacciNumberBeyondPrevious = 0; var fibonacciNumPrevious = 1; var fibonacciNum = fibonacciNumPrevious; while (fibonacciNum <= arrayLength) { fibonacciNumberBeyondPrevious = fibonacciNumPrevious; fibonacciNumPrevious = fibonacciNum; fibonacciNum = fibonacciNumberBeyondPrevious + fibonacciNumPrevious; } // offset to drop the left part of the array var offset = -1; while (fibonacciNum > 1) { var index = Math.Min(offset + fibonacciNumberBeyondPrevious, arrayLength - 1); switch (item.CompareTo(array[index])) { // reject approximately 1/3 of the existing array in front // by moving Fibonacci numbers case > 0: fibonacciNum = fibonacciNumPrevious; fibonacciNumPrevious = fibonacciNumberBeyondPrevious; fibonacciNumberBeyondPrevious = fibonacciNum - fibonacciNumPrevious; offset = index; break; // reject approximately 2/3 of the existing array behind // by moving Fibonacci numbers case < 0: fibonacciNum = fibonacciNumberBeyondPrevious; fibonacciNumPrevious = fibonacciNumPrevious - fibonacciNumberBeyondPrevious; fibonacciNumberBeyondPrevious = fibonacciNum - fibonacciNumPrevious; break; default: return index; } } // check the last element if (fibonacciNumPrevious == 1 && item.Equals(array[^1])) { return arrayLength - 1; } } return -1; } } }
91
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Search { /// <summary> /// Class that implements interpolation search algorithm. /// </summary> public static class InterpolationSearch { /// <summary> /// Finds the index of the item searched for in the array. /// Algorithm performance: /// worst-case: O(n), /// average-case: O(log(log(n))), /// best-case: O(1). /// </summary> /// <param name="sortedArray">Array with sorted elements to be searched in. Cannot be null.</param> /// <param name="val">Value to be searched for. Cannot be null.</param> /// <returns>If an item is found, return index, else return -1.</returns> public static int FindIndex(int[] sortedArray, int val) { var start = 0; var end = sortedArray.Length - 1; while (start <= end && val >= sortedArray[start] && val <= sortedArray[end]) { var denominator = (sortedArray[end] - sortedArray[start]) * (val - sortedArray[start]); if (denominator == 0) { denominator = 1; } var pos = start + (end - start) / denominator; if (sortedArray[pos] == val) { return pos; } if (sortedArray[pos] < val) { start = pos + 1; } else { end = pos - 1; } } return -1; } } }
53
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search { /// <summary> /// Jump Search checks fewer elements by jumping ahead by fixed steps. /// The optimal steps to jump is √n, where n refers to the number of elements in the array. /// Time Complexity: O(√n) /// Note: The array has to be sorted beforehand. /// </summary> /// <typeparam name="T">Type of the array element.</typeparam> public class JumpSearcher<T> where T : IComparable<T> { /// <summary> /// Find the index of the item searched for in the array. /// </summary> /// <param name="sortedArray">Sorted array to be search in. Cannot be null.</param> /// <param name="searchItem">Item to be search for. Cannot be null.</param> /// <returns>If item is found, return index. If array is empty or item not found, return -1.</returns> public int FindIndex(T[] sortedArray, T searchItem) { if (sortedArray is null) { throw new ArgumentNullException("sortedArray"); } if (searchItem is null) { throw new ArgumentNullException("searchItem"); } int jumpStep = (int)Math.Floor(Math.Sqrt(sortedArray.Length)); int currentIndex = 0; int nextIndex = jumpStep; if (sortedArray.Length != 0) { while (sortedArray[nextIndex - 1].CompareTo(searchItem) < 0) { currentIndex = nextIndex; nextIndex += jumpStep; if (nextIndex >= sortedArray.Length) { nextIndex = sortedArray.Length - 1; break; } } for (int i = currentIndex; i <= nextIndex; i++) { if (sortedArray[i].CompareTo(searchItem) == 0) { return i; } } } return -1; } } }
63
C-Sharp
TheAlgorithms
C#
using System; using Utilities.Exceptions; namespace Algorithms.Search { /// <summary> /// Class that implements linear search algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class LinearSearcher<T> { /// <summary> /// Finds first item in array that satisfies specified term /// Time complexity: O(n) /// Space complexity: O(1). /// </summary> /// <param name="data">Array to search in.</param> /// <param name="term">Term to check against.</param> /// <returns>First item that satisfies term.</returns> public T Find(T[] data, Func<T, bool> term) { for (var i = 0; i < data.Length; i++) { if (term(data[i])) { return data[i]; } } throw new ItemNotFoundException(); } /// <summary> /// Finds index of first item in array that satisfies specified term /// Time complexity: O(n) /// Space complexity: O(1). /// </summary> /// <param name="data">Array to search in.</param> /// <param name="term">Term to check against.</param> /// <returns>Index of first item that satisfies term or -1 if none found.</returns> public int FindIndex(T[] data, Func<T, bool> term) { for (var i = 0; i < data.Length; i++) { if (term(data[i])) { return i; } } return -1; } } }
55
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Search { /// <summary> /// RecursiveBinarySearcher. /// </summary> /// <typeparam name="T">Type of searcher target.</typeparam> public class RecursiveBinarySearcher<T> where T : IComparable<T> { /// <summary> /// Finds index of item in collection that equals to item searched for, /// time complexity: O(log(n)), /// space complexity: O(1), /// where n - collection size. /// </summary> /// <param name="collection">Sorted collection to search in.</param> /// <param name="item">Item to search for.</param> /// <exception cref="ArgumentNullException">Thrown if input collection is null.</exception> /// <returns>Index of item that equals to item searched for or -1 if none found.</returns> public int FindIndex(IList<T>? collection, T item) { if (collection is null) { throw new ArgumentNullException(nameof(collection)); } var leftIndex = 0; var rightIndex = collection.Count - 1; return FindIndex(collection, item, leftIndex, rightIndex); } /// <summary> /// Finds index of item in array that equals to item searched for, /// time complexity: O(log(n)), /// space complexity: O(1), /// where n - array size. /// </summary> /// <param name="collection">Sorted array to search in.</param> /// <param name="item">Item to search for.</param> /// <param name="leftIndex">Minimum search range.</param> /// <param name="rightIndex">Maximum search range.</param> /// <returns>Index of item that equals to item searched for or -1 if none found.</returns> private int FindIndex(IList<T> collection, T item, int leftIndex, int rightIndex) { if (leftIndex > rightIndex) { return -1; } var middleIndex = leftIndex + (rightIndex - leftIndex) / 2; var result = item.CompareTo(collection[middleIndex]); return result switch { var r when r == 0 => middleIndex, var r when r > 0 => FindIndex(collection, item, middleIndex + 1, rightIndex), var r when r < 0 => FindIndex(collection, item, leftIndex, middleIndex - 1), _ => -1, }; } } }
66
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Search.AStar { /// <summary> /// Contains the code for A* Pathfinding. /// </summary> public static class AStar { /// <summary> /// Resets the Nodes in the list. /// </summary> /// <param name="nodes">Resets the nodes to be used again.</param> public static void ResetNodes(List<Node> nodes) { foreach (var node in nodes) { node.CurrentCost = 0; node.EstimatedCost = 0; node.Parent = null; node.State = NodeState.Unconsidered; } } /// <summary> /// Generates the Path from an (solved) node graph, before it gets reset. /// </summary> /// <param name="target">The node where we want to go.</param> /// <returns>The Path to the target node.</returns> public static List<Node> GeneratePath(Node target) { var ret = new List<Node>(); var current = target; while (!(current is null)) { ret.Add(current); current = current.Parent; } ret.Reverse(); return ret; } /// <summary> /// Computes the path from => to. /// </summary> /// <param name="from">Start node.</param> /// <param name="to">end node.</param> /// <returns>Path from start to end.</returns> public static List<Node> Compute(Node from, Node to) { var done = new List<Node>(); // A priority queue that will sort our nodes based on the total cost estimate var open = new PriorityQueue<Node>(); foreach (var node in from.ConnectedNodes) { // Add connecting nodes if traversable if (node.Traversable) { // Calculate the Costs node.CurrentCost = from.CurrentCost + from.DistanceTo(node) * node.TraversalCostMultiplier; node.EstimatedCost = from.CurrentCost + node.DistanceTo(to); // Enqueue open.Enqueue(node); } } while (true) { // End Condition( Path not found ) if (open.Count == 0) { ResetNodes(done); ResetNodes(open.GetData()); return new List<Node>(); } // Selecting next Element from queue var current = open.Dequeue(); // Add it to the done list done.Add(current); current.State = NodeState.Closed; // EndCondition( Path was found ) if (current == to) { var ret = GeneratePath(to); // Create the Path // Reset all Nodes that were used. ResetNodes(done); ResetNodes(open.GetData()); return ret; } AddOrUpdateConnected(current, to, open); } } private static void AddOrUpdateConnected(Node current, Node to, PriorityQueue<Node> queue) { foreach (var connected in current.ConnectedNodes) { if (!connected.Traversable || connected.State == NodeState.Closed) { continue; // Do ignore already checked and not traversable nodes. } // Adds a previously not "seen" node into the Queue if (connected.State == NodeState.Unconsidered) { connected.Parent = current; connected.CurrentCost = current.CurrentCost + current.DistanceTo(connected) * connected.TraversalCostMultiplier; connected.EstimatedCost = connected.CurrentCost + connected.DistanceTo(to); connected.State = NodeState.Open; queue.Enqueue(connected); } else if (current != connected) { // Updating the cost of the node if the current way is cheaper than the previous var newCCost = current.CurrentCost + current.DistanceTo(connected); var newTCost = newCCost + current.EstimatedCost; if (newTCost < connected.TotalCost) { connected.Parent = current; connected.CurrentCost = newCCost; } } else { // Codacy made me do it. throw new PathfindingException( "Detected the same node twice. Confusion how this could ever happen"); } } } } }
144
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search.AStar { /// <summary> /// Contains Positional and other information about a single node. /// </summary> public class Node : IComparable<Node>, IEquatable<Node> { public Node(VecN position, bool traversable, double traverseMultiplier) { Traversable = traversable; Position = position; TraversalCostMultiplier = traverseMultiplier; } /// <summary> /// Gets the Total cost of the Node. /// The Current Costs + the estimated costs. /// </summary> public double TotalCost => EstimatedCost + CurrentCost; /// <summary> /// Gets or sets the Distance between this node and the target node. /// </summary> public double EstimatedCost { get; set; } /// <summary> /// Gets a value indicating whether how costly it is to traverse over this node. /// </summary> public double TraversalCostMultiplier { get; } /// <summary> /// Gets or sets a value indicating whether to go from the start node to this node. /// </summary> public double CurrentCost { get; set; } /// <summary> /// Gets or sets the state of the Node /// Can be Unconsidered(Default), Open and Closed. /// </summary> public NodeState State { get; set; } /// <summary> /// Gets a value indicating whether the node is traversable. /// </summary> public bool Traversable { get; } /// <summary> /// Gets or sets a list of all connected nodes. /// </summary> public Node[] ConnectedNodes { get; set; } = new Node[0]; /// <summary> /// Gets or sets he "previous" node that was processed before this node. /// </summary> public Node? Parent { get; set; } /// <summary> /// Gets the positional information of the node. /// </summary> public VecN Position { get; } /// <summary> /// Compares the Nodes based on their total costs. /// Total Costs: A* Pathfinding. /// Current: Djikstra Pathfinding. /// Estimated: Greedy Pathfinding. /// </summary> /// <param name="other">The other node.</param> /// <returns>A comparison between the costs.</returns> public int CompareTo(Node? other) => TotalCost.CompareTo(other?.TotalCost ?? 0); public bool Equals(Node? other) => CompareTo(other) == 0; public static bool operator ==(Node left, Node right) => left?.Equals(right) != false; public static bool operator >(Node left, Node right) => left.CompareTo(right) > 0; public static bool operator <(Node left, Node right) => left.CompareTo(right) < 0; public static bool operator !=(Node left, Node right) => !(left == right); public static bool operator <=(Node left, Node right) => left.CompareTo(right) <= 0; public static bool operator >=(Node left, Node right) => left.CompareTo(right) >= 0; public override bool Equals(object? obj) => obj is Node other && Equals(other); public override int GetHashCode() => Position.GetHashCode() + Traversable.GetHashCode() + TraversalCostMultiplier.GetHashCode(); /// <summary> /// Returns the distance to the other node. /// </summary> /// <param name="other">The other node.</param> /// <returns>Distance between this and other.</returns> public double DistanceTo(Node other) => Math.Sqrt(Position.SqrDistance(other.Position)); } }
103
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Search.AStar { /// <summary> /// The states the nodes can have. /// </summary> public enum NodeState { /// <summary> /// TODO. /// </summary> Unconsidered = 0, /// <summary> /// TODO. /// </summary> Open = 1, /// <summary> /// TODO. /// </summary> Closed = 2, } }
24
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search.AStar { /// <summary> /// A pathfinding exception is thrown when the Pathfinder encounters a critical error and can not continue. /// </summary> public class PathfindingException : Exception { public PathfindingException(string message) : base(message) { } } }
16
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; // todo: extract to data structures namespace Algorithms.Search.AStar { /// <summary> /// Generic Priority Queue. /// List based. /// </summary> /// <typeparam name="T"> /// The type that will be stored. /// Has to be IComparable of T. /// </typeparam> public class PriorityQueue<T> where T : IComparable<T> { private readonly bool isDescending; // The underlying structure. private readonly List<T> list; public PriorityQueue(bool isDescending = false) { this.isDescending = isDescending; list = new List<T>(); } /// <summary> /// Initializes a new instance of the <see cref="PriorityQueue{T}" /> class. /// </summary> /// <param name="capacity">Initial capacity.</param> /// <param name="isDescending">Should Reverse Sort order? Default: false.</param> public PriorityQueue(int capacity, bool isDescending = false) { list = new List<T>(capacity); this.isDescending = isDescending; } /// <summary> /// Initializes a new instance of the <see cref="PriorityQueue{T}" /> class. /// </summary> /// <param name="collection">Internal data.</param> /// <param name="isDescending">Should Reverse Sort order? Default: false.</param> public PriorityQueue(IEnumerable<T> collection, bool isDescending = false) : this() { this.isDescending = isDescending; foreach (var item in collection) { Enqueue(item); } } /// <summary> /// Gets Number of enqueued items. /// </summary> public int Count => list.Count; /// <summary> /// Enqueues an item into the Queue. /// </summary> /// <param name="x">The item to Enqueue.</param> public void Enqueue(T x) { list.Add(x); var i = Count - 1; // Position of x while (i > 0) { var p = (i - 1) / 2; // Start at half of i if ((isDescending ? -1 : 1) * list[p].CompareTo(x) <= 0) { break; } list[i] = list[p]; // Put P to position of i i = p; // I = (I-1)/2 } if (Count > 0) { list[i] = x; // If while loop way executed at least once(X got replaced by some p), add it to the list } } /// <summary> /// Dequeues the item at the end of the queue. /// </summary> /// <returns>The dequeued item.</returns> public T Dequeue() { var target = Peek(); // Get first in list var root = list[Count - 1]; // Hold last of the list list.RemoveAt(Count - 1); // But remove it from the list var i = 0; while (i * 2 + 1 < Count) { var a = i * 2 + 1; // Every second entry starting by 1 var b = i * 2 + 2; // Every second entries neighbour var c = b < Count && (isDescending ? -1 : 1) * list[b].CompareTo(list[a]) < 0 ? b : a; // Whether B(B is in range && B is smaller than A) or A if ((isDescending ? -1 : 1) * list[c].CompareTo(root) >= 0) { break; } list[i] = list[c]; i = c; } if (Count > 0) { list[i] = root; } return target; } /// <summary> /// Returns the next element in the queue without dequeuing. /// </summary> /// <returns>The next element of the queue.</returns> public T Peek() { if (Count == 0) { throw new InvalidOperationException("Queue is empty."); } return list[0]; } /// <summary> /// Clears the Queue. /// </summary> public void Clear() => list.Clear(); /// <summary> /// Returns the Internal Data. /// </summary> /// <returns>The internal data structure.</returns> public List<T> GetData() => list; } }
149
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Search.AStar { /// <summary> /// Vector Struct with N Dimensions. /// </summary> public struct VecN : IEquatable<VecN> { private readonly double[] data; /// <summary> /// Initializes a new instance of the <see cref="VecN" /> struct. /// </summary> /// <param name="vals">Vector components as array.</param> public VecN(params double[] vals) => data = vals; /// <summary> /// Gets the dimension count of this vector. /// </summary> public int N => data.Length; /// <summary> /// Returns the Length squared. /// </summary> /// <returns>The squared length of the vector.</returns> public double SqrLength() { double ret = 0; for (var i = 0; i < data.Length; i++) { ret += data[i] * data[i]; } return ret; } /// <summary> /// Returns the Length of the vector. /// </summary> /// <returns>Length of the Vector.</returns> public double Length() => Math.Sqrt(SqrLength()); /// <summary> /// Returns the Distance between this and other. /// </summary> /// <param name="other">Other vector.</param> /// <returns>The distance between this and other.</returns> public double Distance(VecN other) { var delta = Subtract(other); return delta.Length(); } /// <summary> /// Returns the squared Distance between this and other. /// </summary> /// <param name="other">Other vector.</param> /// <returns>The squared distance between this and other.</returns> public double SqrDistance(VecN other) { var delta = Subtract(other); return delta.SqrLength(); } /// <summary> /// Substracts other from this vector. /// </summary> /// <param name="other">Other vector.</param> /// <returns>The new vector.</returns> public VecN Subtract(VecN other) { var dd = new double[Math.Max(data.Length, other.data.Length)]; for (var i = 0; i < dd.Length; i++) { double val = 0; if (data.Length > i) { val = data[i]; } if (other.data.Length > i) { val -= other.data[i]; } dd[i] = val; } return new VecN(dd); } /// <summary> /// Is used to compare Vectors with each other. /// </summary> /// <param name="other">The vector to be compared.</param> /// <returns>A value indicating if other has the same values as this.</returns> public bool Equals(VecN other) { if (other.N != N) { return false; } for (var i = 0; i < other.data.Length; i++) { if (Math.Abs(data[i] - other.data[i]) > 0.000001) { return false; } } return true; } } }
117
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// The all ones sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A000012. /// </para> /// </summary> public class AllOnesSequence : ISequence { /// <summary> /// Gets all ones sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { while (true) { yield return 1; } } } }
30
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// The all threes sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A010701. /// </para> /// </summary> public class AllThreesSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { while (true) { yield return 3; } } } }
27
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// The all twos sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A007395. /// </para> /// </summary> public class AllTwosSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { while (true) { yield return 2; } } } }
27
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of binary prime constant /// (Characteristic function of primes: 1 if n is prime, else 0). /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Prime_constant. /// </para> /// <para> /// OEIS: https://oeis.org/A010051. /// </para> /// </summary> public class BinaryPrimeConstantSequence : ISequence { /// <summary> /// Gets sequence of binary prime constant. /// </summary> public IEnumerable<BigInteger> Sequence { get { ISequence primes = new PrimesSequence(); var n = new BigInteger(0); foreach (var p in primes.Sequence) { for (n++; n < p; n++) { yield return 0; } yield return 1; } } } } }
43
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of binomial coefficients. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient. /// </para> /// <para> /// OEIS: http://oeis.org/A007318. /// </para> /// </summary> public class BinomialSequence : ISequence { /// <summary> /// Gets sequence of binomial coefficients. /// </summary> public IEnumerable<BigInteger> Sequence { get { var i = 0; while (true) { var row = GenerateRow(i); foreach (var coefficient in row) { yield return coefficient; } i++; } } } private static BigInteger BinomialCoefficient(long n, long k) { if (k == 0 || k == n) { return new BigInteger(1); } if (n < 0) { return new BigInteger(0); } return BinomialCoefficient(n - 1, k) + BinomialCoefficient(n - 1, k - 1); } private static IEnumerable<BigInteger> GenerateRow(long n) { long k = 0; while (k <= n) { yield return BinomialCoefficient(n, k); k++; } } } }
68
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Cake numbers: maximal number of pieces resulting from n planar cuts through a cube /// (or cake): C(n+1,3) + n + 1. /// </para> /// <para> /// OEIS: https://oeis.org/A000125. /// </para> /// </summary> public class CakeNumbersSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(0); while (true) { var next = (BigInteger.Pow(n, 3) + 5 * n + 6) / 6; n++; yield return next; } } } }
31
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Catalan numbers: C[n+1] = (2*(2*n+1)*C[n])/(n+2). /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Catalan_number. /// </para> /// <para> /// OEIS:http://oeis.org/A000108. /// </para> /// </summary> public class CatalanSequence : ISequence { /// <summary> /// Gets sequence of Catalan numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { // initialize the first element (1) and define it's enumerator (0) var catalan = new BigInteger(1); var n = 0; while (true) { yield return catalan; catalan = (2 * (2 * n + 1) * catalan) / (n + 2); n++; } } } } }
39
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Central polygonal numbers (the Lazy Caterer's sequence): n(n+1)/2 + 1; or, maximal number of pieces /// formed when slicing a pancake with n cuts. /// </para> /// <para> /// OEIS: https://oeis.org/A000124. /// </para> /// </summary> public class CentralPolygonalNumbersSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(0); while (true) { var next = n * (n + 1) / 2 + 1; n++; yield return next; } } } }
31
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of cube numbers. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Cube_(algebra). /// </para> /// <para> /// OEIS: https://oeis.org/A000578. /// </para> /// </summary> public class CubesSequence : ISequence { /// <summary> /// Gets sequence of cube numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = BigInteger.Zero; while (true) { yield return n * n * n; n++; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of the number of divisors of n, starting with 1. /// </para> /// <para> /// OEIS: https://oeis.org/A000005. /// </para> /// </summary> public class DivisorsCountSequence : ISequence { /// <summary> /// Gets sequence of number of divisors for n, starting at 1. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return BigInteger.One; for (var n = new BigInteger(2); ; n++) { var count = 2; for (var k = 2; k < n; k++) { BigInteger.DivRem(n, k, out var remainder); if (remainder == 0) { count++; } } yield return count; } } } } }
42
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Euclid numbers: 1 + product of the first n primes. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Euclid_number. /// </para> /// <para> /// OEIS: https://oeis.org/A006862. /// </para> /// </summary> public class EuclidNumbersSequence : ISequence { /// <summary> /// Gets sequence of Euclid numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var primorialNumbers = new PrimorialNumbersSequence().Sequence; foreach (var n in primorialNumbers) { yield return n + 1; } } } } }
36
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Euler totient function phi(n). /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Euler%27s_totient_function. /// </para> /// <para> /// OEIS: https://oeis.org/A000010. /// </para> /// </summary> public class EulerTotientSequence : ISequence { /// <summary> /// <para> /// Gets sequence of Euler totient function phi(n). /// </para> /// <para> /// 'n' is copied from value of the loop of i that's being enumerated over. /// 1) Initialize result as n /// 2) Consider every number 'factor' (where 'factor' is a prime divisor of n). /// If factor divides n, then do following /// a) Subtract all multiples of factor from 1 to n [all multiples of factor /// will have gcd more than 1 (at least factor) with n] /// b) Update n by repeatedly dividing it by factor. /// 3) If the reduced n is more than 1, then remove all multiples /// of n from result. /// </para> /// <para> /// Base code was from https://www.geeksforgeeks.org/eulers-totient-function/. /// </para> /// <para> /// Implementation avoiding floating point operations was used for base /// and replacement of loop going from 1 to sqrt(n) was replaced with /// List of prime factors. /// </para> /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return BigInteger.One; for (BigInteger i = 2; ; i++) { var n = i; var result = n; var factors = PrimeFactors(i); foreach (var factor in factors) { while (n % factor == 0) { n /= factor; } result -= result / factor; } if (n > 1) { result -= result / n; } yield return result; } } } /// <summary> /// <para> /// Uses the prime sequence to find all prime factors of the /// number we're looking at. /// </para> /// <para> /// The prime sequence is examined until its value squared is /// less than or equal to target, and checked to make sure it /// evenly divides the target. If it evenly divides, it's added /// to the result which is returned as a List. /// </para> /// </summary> /// <param name="target">Number that is being factored.</param> /// <returns>List of prime factors of target.</returns> private static IEnumerable<BigInteger> PrimeFactors(BigInteger target) { return new PrimesSequence() .Sequence.TakeWhile(prime => prime * prime <= target) .Where(prime => target % prime == 0) .ToList(); } } }
99
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of factorial numbers. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Factorial. /// </para> /// <para> /// OEIS: https://oeis.org/A000142. /// </para> /// </summary> public class FactorialSequence : ISequence { /// <summary> /// Gets sequence of factorial numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = 0; var factorial = new BigInteger(1); while (true) { yield return factorial; n++; factorial *= n; } } } } }
38
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Fermat numbers: a(n) = 2^(2^n) + 1. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Fermat_number. /// </para> /// <para> /// OEIS: https://oeis.org/A000215. /// </para> /// </summary> public class FermatNumbersSequence : ISequence { /// <summary> /// Gets sequence of Fermat numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(2); while (true) { yield return n + 1; n *= n; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Fermat primes: primes of the form 2^(2^k) + 1, for some k >= 0. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Fermat_number. /// </para> /// <para> /// OEIS: https://oeis.org/A019434. /// </para> /// </summary> public class FermatPrimesSequence : ISequence { /// <summary> /// Gets sequence of Fermat primes. /// </summary> public IEnumerable<BigInteger> Sequence { get { var fermatNumbers = new FermatNumbersSequence().Sequence.Take(5); foreach (var n in fermatNumbers) { yield return n; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Fibonacci sequence. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Fibonacci_number. /// </para> /// <para> /// OEIS: https://oeis.org/A000045. /// </para> /// </summary> public class FibonacciSequence : ISequence { /// <summary> /// Gets Fibonacci sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 0; yield return 1; BigInteger previous = 0; BigInteger current = 1; while (true) { var next = previous + current; previous = current; current = next; yield return next; } } } } }
41
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Golomb's sequence. a(n) is the number of times n occurs in the sequence, starting with a(1) = 1. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Golomb_sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A001462. /// </para> /// </summary> public class GolombsSequence : ISequence { /// <summary> /// Gets Golomb's sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 1; yield return 2; yield return 2; var queue = new Queue<BigInteger>(); queue.Enqueue(2); for (var i = 3; ; i++) { var repetitions = queue.Dequeue(); for (var j = 0; j < repetitions; j++) { queue.Enqueue(i); yield return i; } } } } } }
47
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// Common interface for all integer sequences. /// </summary> public interface ISequence { /// <summary> /// Gets sequence as enumerable. /// </summary> IEnumerable<BigInteger> Sequence { get; } } }
17
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Kolakoski sequence; n-th element is the length of the n-th run in the sequence itself. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Kolakoski_sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A000002. /// </para> /// </summary> public class KolakoskiSequence : ISequence { /// <summary> /// Gets Kolakoski sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 1; yield return 2; yield return 2; var queue = new Queue<int>(); queue.Enqueue(2); var nextElement = 1; while (true) { var nextRun = queue.Dequeue(); for (var i = 0; i < nextRun; i++) { queue.Enqueue(nextElement); yield return nextElement; } nextElement = 1 + nextElement % 2; } } } } }
48
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Kolakoski sequence; n-th element is the length of the n-th run in the sequence itself. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Kolakoski_sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A000002. /// </para> /// </summary> public class KolakoskiSequence2 : ISequence { /// <summary> /// Gets Kolakoski sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 1; yield return 2; yield return 2; var inner = new KolakoskiSequence2().Sequence.Skip(2); var nextElement = 1; foreach (var runLength in inner) { yield return nextElement; if (runLength > 1) { yield return nextElement; } nextElement = 1 + nextElement % 2; } } } } }
47
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Kummer numbers (also called Euclid numbers of the second kind): /// -1 + product of first n consecutive primes. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Euclid_number. /// </para> /// <para> /// OEIS: https://oeis.org/A057588. /// </para> /// </summary> public class KummerNumbersSequence : ISequence { /// <summary> /// Gets sequence of Kummer numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var primorialNumbers = new PrimorialNumbersSequence().Sequence.Skip(1); foreach (var n in primorialNumbers) { yield return n - 1; } } } } }
38
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of Lucas number values. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Lucas_number. /// </para> /// <para> /// OEIS: http://oeis.org/A000032. /// </para> /// </summary> public class LucasNumbersBeginningAt2Sequence : ISequence { /// <summary> /// <para> /// Gets Lucas number sequence. /// </para> /// <para> /// Lucas numbers follow the same type of operation that the Fibonacci (A000045) /// sequence performs with starting values of 2, 1 versus 0,1. As Fibonacci does, /// the ratio between two consecutive Lucas numbers converges to phi. /// </para> /// <para> /// This implementation is similar to A000204, but starts with the index of 0, thus having the /// initial values being (2,1) instead of starting at index 1 with initial values of (1,3). /// </para> /// <para> /// A simple relationship to Fibonacci can be shown with L(n) = F(n-1) + F(n+1), n>= 1. /// /// n | L(n) | F(n-1) | F(n+1) /// --|-------|--------+--------+ /// 0 | 2 | | | /// 1 | 1 | 0 | 1 | /// 2 | 3 | 1 | 2 | /// 3 | 4 | 1 | 3 | /// 4 | 7 | 2 | 5 | /// 5 | 11 | 3 | 8 | /// --|-------|--------+--------+. /// </para> /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 2; yield return 1; BigInteger previous = 2; BigInteger current = 1; while (true) { var next = previous + current; previous = current; current = next; yield return next; } } } } }
66
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Number of ways of making change for n cents using coins of 1, 2, 5, 10 cents. /// </para> /// <para> /// OEIS: https://oeis.org/A000008. /// </para> /// </summary> public class MakeChangeSequence : ISequence { /// <summary> /// <para> /// Gets sequence of number of ways of making change for n cents /// using coins of 1, 2, 5, 10 cents. /// </para> /// <para> /// Uses formula from OEIS page by Michael Somos /// along with first 17 values to prevent index issues. /// </para> /// <para> /// Formula: /// a(n) = a(n-2) +a(n-5) - a(n-7) + a(n-10) - a(n-12) - a(n-15) + a(n-17) + 1. /// </para> /// </summary> public IEnumerable<BigInteger> Sequence { get { var seed = new List<BigInteger> { 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 11, 12, 15, 16, 19, 22, 25, }; foreach (var value in seed) { yield return value; } for(var index = 17; ; index++) { BigInteger newValue = seed[index - 2] + seed[index - 5] - seed[index - 7] + seed[index - 10] - seed[index - 12] - seed[index - 15] + seed[index - 17] + 1; seed.Add(newValue); yield return newValue; } } } } }
58
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Sequence of number of triangles in triangular matchstick arrangement of side n for n>=0. /// </para> /// <para> /// M. E. Larsen, The eternal triangle – a history of a counting problem, College Math. J., 20 (1989), 370-392. /// https://web.math.ku.dk/~mel/mel.pdf. /// </para> /// <para> /// OEIS: http://oeis.org/A002717. /// </para> /// </summary> public class MatchstickTriangleSequence : ISequence { /// <summary> /// <para> /// Gets number of triangles contained in an triangular arrangement of matchsticks of side length n. /// </para> /// <para> /// This also counts the subset of smaller triangles contained within the arrangement. /// </para> /// <para> /// Based on the PDF referenced above, the sequence is derived from step 8, using the resulting equation /// of f(n) = (n(n+2)(2n+1) -(delta)(n)) / 8. Using BigInteger values, we can effectively remove /// (delta)(n) from the previous by using integer division instead. /// </para> /// <para> /// Examples follow. /// <pre> /// . /// / \ This contains 1 triangle of size 1. /// .---. /// /// . /// / \ This contains 4 triangles of size 1. /// .---. This contains 1 triangle of size 2. /// / \ / \ This contains 5 triangles total. /// .---.---. /// /// . /// / \ This contains 9 triangles of size 1. /// .---. This contains 3 triangles of size 2. /// / \ / \ This contains 1 triangles of size 3. /// .---.---. /// / \ / \ / \ This contains 13 triangles total. /// .---.---.---. /// </pre> /// </para> /// </summary> public IEnumerable<BigInteger> Sequence { get { var index = BigInteger.Zero; var eight = new BigInteger(8); while (true) { var temp = index * (index + 2) * (index * 2 + 1); var result = BigInteger.Divide(temp, eight); yield return result; index++; } } } }
72
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of natural numbers. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Natural_number. /// </para> /// <para> /// OEIS: https://oeis.org/A000027. /// </para> /// </summary> public class NaturalSequence : ISequence { /// <summary> /// Gets sequence of natural numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(1); while (true) { yield return n++; } } } } }
35
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of negative integers. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Negative_number. /// </para> /// <para> /// OEIS: http://oeis.org/A001478. /// </para> /// </summary> public class NegativeIntegersSequence : ISequence { /// <summary> /// Gets sequence of negative integers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(-1); while (true) { yield return n--; } } } } }
36
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of number of truth tables generated by Boolean expressions of n variables /// (Double exponentials of 2: a(n) = 2^(2^n)). /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Truth_table. /// </para> /// <para> /// OEIS: https://oeis.org/A001146. /// </para> /// </summary> public class NumberOfBooleanFunctionsSequence : ISequence { /// <summary> /// Gets sequence of number Of Boolean functions. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(2); while (true) { yield return n; n *= n; } } } } }
38
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Number of primes with n digits /// (The number of primes between 10^(n-1) and 10^n). /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. /// </para> /// <para> /// OEIS: https://oeis.org/A006879. /// </para> /// </summary> public class NumberOfPrimesByNumberOfDigitsSequence : ISequence { /// <summary> /// Gets sequence of number of primes. /// </summary> public IEnumerable<BigInteger> Sequence { get { ISequence primes = new PrimesSequence(); var powerOf10 = new BigInteger(1); var counter = new BigInteger(0); foreach (var p in primes.Sequence) { if (p > powerOf10) { yield return counter; counter = 0; powerOf10 *= 10; } counter++; } } } } }
46
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of number of primes less than 10^n (with at most n digits). /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. /// </para> /// <para> /// OEIS: https://oeis.org/A006880. /// </para> /// </summary> public class NumberOfPrimesByPowersOf10Sequence : ISequence { /// <summary> /// Gets sequence of numbers of primes. /// </summary> public IEnumerable<BigInteger> Sequence { get { ISequence primes = new PrimesSequence(); var powerOf10 = new BigInteger(1); var counter = new BigInteger(0); foreach (var p in primes.Sequence) { if (p > powerOf10) { yield return counter; powerOf10 *= 10; } counter++; } } } } }
44
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// 1's-counting sequence: number of 1's in binary expression of n. /// </para> /// <para> /// OEIS: https://oeis.org/A000120. /// </para> /// </summary> public class OnesCountingSequence : ISequence { /// <summary> /// <para> /// Gets the generated sequence of the 1's contained in the binary representation of n. /// </para> /// <para> /// The sequence is generated as follows. /// 1. The initial 0 value is provided. /// 2. A recursively generated sequence is iterated, starting with a length of 1 (i.e., 2^0), /// followed by increasing 2^x length values. /// 3. Each sequence starts with the value 1, and a targeted value of depths that it will recurse /// for the specific iteration. /// 4. If the call depth to the recursive function is met, it returns the value argument received. /// 5. If the call depth has not been met, it recurses to create 2 sequences, one starting with the /// value argument, and the following with the value argument + 1. /// 6. Using ':' as a visual separator for each sequence, this results in the following sequences /// that are returned sequentially after the initial 0. /// 1 : 1, 2 : 1, 2, 2, 3 : 1, 2, 2, 3, 2, 3, 3, 4. /// </para> /// <remarks> /// <para> /// This one comes from thinking over information contained within the COMMENTS section of the OEIS page. /// </para> /// <para> /// Using the comments provided by Benoit Cloitre, Robert G. Wilson v, and Daniel Forgues, the above /// algorithm was coded. /// </para> /// </remarks> /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 0; var depth = 0; while (true) { foreach (var count in GenerateFractalCount(BigInteger.One, depth)) { yield return count; } depth++; } } } /// <summary> /// <para> /// Recursive function to generate sequences. /// </para> /// </summary> /// <param name="i">The value that will start off the current IEnumerable sequence.</param> /// <param name="depth">The remaining depth of recursion. Value of 0 is the stop condition.</param> /// <returns>An IEnumerable sequence of BigInteger values that can be iterated over.</returns> private static IEnumerable<BigInteger> GenerateFractalCount(BigInteger i, int depth) { // Terminal condition if (depth == 0) { yield return i; yield break; } foreach (var firstHalf in GenerateFractalCount(i, depth - 1)) { yield return firstHalf; } foreach (var secondHalf in GenerateFractalCount(i + 1, depth - 1)) { yield return secondHalf; } } }
90
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of powers of 10: a(n) = 10^n. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Power_of_10. /// </para> /// <para> /// OEIS: https://oeis.org/A011557. /// </para> /// </summary> public class PowersOf10Sequence : ISequence { /// <summary> /// Gets sequence of powers of 10. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(1); while (true) { yield return n; n *= 10; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of powers of 2: a(n) = 2^n. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Power_of_two. /// </para> /// <para> /// OEIS: https://oeis.org/A000079. /// </para> /// </summary> public class PowersOf2Sequence : ISequence { /// <summary> /// Gets sequence of powers of 2. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(1); while (true) { yield return n; n *= 2; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of number of primes less than or equal to n (PrimePi(n)). /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. /// </para> /// <para> /// OEIS: https://oeis.org/A000720. /// </para> /// </summary> public class PrimePiSequence : ISequence { /// <summary> /// Gets sequence of number of primes. /// </summary> public IEnumerable<BigInteger> Sequence { get { ISequence primes = new PrimesSequence(); var n = new BigInteger(0); var counter = new BigInteger(0); foreach (var p in primes.Sequence) { for (n++; n < p; n++) { yield return counter; } yield return ++counter; } } } } }
43
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of prime numbers. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Prime_number. /// </para> /// <para> /// OEIS: https://oeis.org/A000040. /// </para> /// </summary> public class PrimesSequence : ISequence { /// <summary> /// Gets sequence of prime numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 2; var primes = new List<BigInteger> { 2, }; var n = new BigInteger(3); while (true) { if (primes.All(p => n % p != 0)) { yield return n; primes.Add(n); } n += 2; } } } } }
48
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of primorial numbers: product of first n primes. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Primorial. /// </para> /// <para> /// OEIS: https://oeis.org/A002110. /// </para> /// </summary> public class PrimorialNumbersSequence : ISequence { /// <summary> /// Gets sequence of primorial numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var primes = new PrimesSequence().Sequence; var n = new BigInteger(1); foreach (var p in primes) { yield return n; n *= p; } } } } }
38
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Recaman's sequence. a(0) = 0; for n > 0, a(n) = a(n-1) - n if nonnegative and not already in the sequence, otherwise a(n) = a(n-1) + n. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence. /// </para> /// <para> /// OEIS: http://oeis.org/A005132. /// </para> /// </summary> public class RecamansSequence : ISequence { /// <summary> /// Gets Recaman's sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 0; var elements = new HashSet<BigInteger> { 0 }; var previous = 0; var i = 1; while (true) { var current = previous - i; if (current < 0 || elements.Contains(current)) { current = previous + i; } yield return current; previous = current; elements.Add(current); i++; } } } } }
48
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Sequence of square numbers. /// </para> /// <para> /// Wikipedia: https://wikipedia.org/wiki/Square_number. /// </para> /// <para> /// OEIS: http://oeis.org/A000290. /// </para> /// </summary> public class SquaresSequence : ISequence { /// <summary> /// Gets sequence of square numbers. /// </summary> public IEnumerable<BigInteger> Sequence { get { var n = new BigInteger(0); while (true) { yield return n * n; n++; } } } } }
37
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Sequence of tetrahedral (triangular pyramids) counts for n >= 0. /// </para> /// <para> /// OEIS: http://oeis.org/A000292. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Tetrahedral_number. /// </para> /// </summary> public class TetrahedralSequence : ISequence { /// <summary> /// <para> /// Gets the value of packing spheres in a regular tetrahedron /// with increasing by 1 triangular numbers under each layer. /// </para> /// <para> /// It can be reviewed by starting at the 4th row of Pascal's Triangle /// following the diagonal values going into the triangle. /// </para> /// </summary> public IEnumerable<BigInteger> Sequence { get { var index = BigInteger.Zero; var six = new BigInteger(6); while (true) { yield return BigInteger.Divide(index * (index + 1) * (index + 2), six); index++; } } } }
43
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Tetranacci numbers: a(n) = a(n-1) + a(n-2) + a(n-3) + a(n-4) with a(0) = a(1) = a(2) = a(3) = 1. /// </para> /// <para> /// OEIS: https://oeis.org/A000288. /// </para> /// </summary> public class TetranacciNumbersSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { var buffer = Enumerable.Repeat(BigInteger.One, 4).ToArray(); while (true) { yield return buffer[0]; var next = buffer[0] + buffer[1] + buffer[2] + buffer[3]; buffer[0] = buffer[1]; buffer[1] = buffer[2]; buffer[2] = buffer[3]; buffer[3] = next; } } } }
34
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Number of halving and tripling steps to reach 1 in the '3n+1' problem. /// </para> /// <para> /// Wikipedia: https://en.wikipedia.org/wiki/Collatz_conjecture. /// </para> /// <para> /// OEIS: https://oeis.org/A006577. /// </para> /// </summary> public class ThreeNPlusOneStepsSequence : ISequence { /// <summary> /// Gets sequence of number of halving and tripling steps to reach 1 in the '3n+1' problem. /// </summary> public IEnumerable<BigInteger> Sequence { get { BigInteger startingValue = 1; while (true) { BigInteger counter = 0; BigInteger currentValue = startingValue; while (currentValue != 1) { if (currentValue.IsEven) { currentValue /= 2; } else { currentValue = 3 * currentValue + 1; } counter++; } yield return counter; startingValue++; } } } } }
54
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Algorithms.Sequences; /// <summary> /// <para> /// Tribonacci numbers: a(n) = a(n-1) + a(n-2) + a(n-3) with a(0)=a(1)=a(2)=1. /// </para> /// <para> /// OEIS: https://oeis.org/A000213. /// </para> /// </summary> public class TribonacciNumbersSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { var buffer = Enumerable.Repeat(BigInteger.One, 4).ToArray(); while (true) { yield return buffer[0]; var next = buffer[0] + buffer[1] + buffer[2]; buffer[0] = buffer[1]; buffer[1] = buffer[2]; buffer[2] = next; } } } }
33
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// Van Eck's sequence. For n >= 1, if there exists an m &lt; n such that a(m) = a(n), take the largest such m and set a(n+1) = n-m; otherwise a(n+1) = 0. Start with a(1)=0. /// </para> /// <para> /// OEIS: http://oeis.org/A181391. /// </para> /// </summary> public class VanEcksSequence : ISequence { /// <summary> /// Gets Van Eck's sequence. /// </summary> public IEnumerable<BigInteger> Sequence { get { yield return 0; var dictionary = new Dictionary<BigInteger, BigInteger>(); BigInteger previous = 0; BigInteger currentIndex = 2; // 1-based index while (true) { BigInteger element = 0; if (dictionary.TryGetValue(previous, out var previousIndex)) { element = currentIndex - previousIndex; } yield return element; dictionary[previous] = currentIndex; previous = element; currentIndex++; } } } } }
45
C-Sharp
TheAlgorithms
C#
using System.Collections; using System.Collections.Generic; using System.Numerics; namespace Algorithms.Sequences { /// <summary> /// <para> /// The zero sequence. /// </para> /// <para> /// OEIS: https://oeis.org/A000004. /// </para> /// </summary> public class ZeroSequence : ISequence { public IEnumerable<BigInteger> Sequence { get { while (true) { yield return 0; } } } } }
29
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Shufflers { /// <summary> /// Fisher-Yates shuffle is a simple shuffling algorithm, /// which is usually used to shuffle a deck of cards. /// </summary> /// <typeparam name="T">Type array input.</typeparam> public class FisherYatesShuffler<T> : IShuffler<T> { /// <summary> /// Shuffles input array using Fisher-Yates algorithm. /// The algorithm starts shuffling from the last element /// and swap elements one by one. We use random index to /// choose element we use in swap operation. /// </summary> /// <param name="array">Array to shuffle.</param> /// <param name="seed">Random generator seed. Used to repeat the shuffle.</param> public void Shuffle(T[] array, int? seed = null) { var random = seed is null ? new Random() : new Random(seed.Value); for (var i = array.Length - 1; i > 0; i--) { var j = random.Next(0, i + 1); (array[i], array[j]) = (array[j], array[i]); } } } }
33
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Shufflers { /// <summary> /// Shuffles array. /// </summary> /// <typeparam name="T">Type of array item.</typeparam> public interface IShuffler<in T> { /// <summary> /// Shuffles array. /// </summary> /// <param name="array">Array to Shuffle.</param> void Shuffle(T[] array, int? seed = null); } }
16
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// TODO. /// </summary> /// <typeparam name="T">TODO. 2.</typeparam> public class BinaryInsertionSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// variant of insertion sort where binary search is used to find place for next element /// internal, in-place, unstable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 1; i < array.Length; i++) { var target = array[i]; var moveIndex = i - 1; var targetInsertLocation = BinarySearch(array, 0, moveIndex, target, comparer); Array.Copy(array, targetInsertLocation, array, targetInsertLocation + 1, i - targetInsertLocation); array[targetInsertLocation] = target; } } /// <summary>Implementation of Binary Search using an iterative approach.</summary> /// <param name="array"> /// An array of values sorted in ascending order between the index values left and right to search /// through. /// </param> /// <param name="from">Left index to search from (inclusive).</param> /// <param name="to">Right index to search to (inclusive).</param> /// <param name="target">The value to find placefor in the provided array.</param> /// <param name="comparer">TODO.</param> /// <returns>The index where to insert target value.</returns> private static int BinarySearch(T[] array, int from, int to, T target, IComparer<T> comparer) { var left = from; var right = to; while (right > left) { var middle = (left + right) / 2; var comparisonResult = comparer.Compare(target, array[middle]); if (comparisonResult == 0) { return middle + 1; } if (comparisonResult > 0) { left = middle + 1; } else { right = middle - 1; } } return comparer.Compare(target, array[left]) < 0 ? left : left + 1; } } }
73
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements bogo sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class BogoSorter<T> : IComparisonSorter<T> { private readonly Random random = new(); /// <summary> /// TODO. /// </summary> /// <param name="array">TODO. 2.</param> /// <param name="comparer">TODO. 3.</param> public void Sort(T[] array, IComparer<T> comparer) { while (!IsSorted(array, comparer)) { Shuffle(array); } } private bool IsSorted(T[] array, IComparer<T> comparer) { for (var i = 0; i < array.Length - 1; i++) { if (comparer.Compare(array[i], array[i + 1]) > 0) { return false; } } return true; } private void Shuffle(T[] array) { var taken = new bool[array.Length]; var newArray = new T[array.Length]; for (var i = 0; i < array.Length; i++) { int nextPos; do { nextPos = random.Next(0, int.MaxValue) % array.Length; } while (taken[nextPos]); taken[nextPos] = true; newArray[nextPos] = array[i]; } for (var i = 0; i < array.Length; i++) { array[i] = newArray[i]; } } } }
64
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements bubble sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class BubbleSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// internal, in-place, stable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 0; i < array.Length - 1; i++) { var wasChanged = false; for (var j = 0; j < array.Length - i - 1; j++) { if (comparer.Compare(array[j], array[j + 1]) > 0) { var temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; wasChanged = true; } } if (!wasChanged) { break; } } } } }
44
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Cocktail Sort is a variation of Bubble sort, where Cocktail /// Sort traverses through a given array in both directions alternatively. /// </summary> /// <typeparam name="T">Array input type.</typeparam> public class CocktailSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using Cocktail sort algorithm. /// </summary> /// <param name="array">Input array.</param> /// <param name="comparer">Type of comparer for array elements.</param> public void Sort(T[] array, IComparer<T> comparer) => CocktailSort(array, comparer); private static void CocktailSort(IList<T> array, IComparer<T> comparer) { var swapped = true; var startIndex = 0; var endIndex = array.Count - 1; while (swapped) { for (var i = startIndex; i < endIndex; i++) { if (comparer.Compare(array[i], array[i + 1]) != 1) { continue; } var highValue = array[i]; array[i] = array[i + 1]; array[i + 1] = highValue; } endIndex--; swapped = false; for (var i = endIndex; i > startIndex; i--) { if (comparer.Compare(array[i], array[i - 1]) != -1) { continue; } var highValue = array[i]; array[i] = array[i - 1]; array[i - 1] = highValue; swapped = true; } startIndex++; } } } }
62
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Comb sort is a relatively simple sorting algorithm that improves on bubble sort. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class CombSorter<T> : IComparisonSorter<T> { public CombSorter(double shrinkFactor = 1.3) => ShrinkFactor = shrinkFactor; private double ShrinkFactor { get; } /// <summary> /// Sorts array using specified comparer, /// internal, in-place, unstable, /// worst case performance: O(n^2), /// best case performance: O(n log(n)), /// average performance: O(n^2 / 2^p), /// space complexity: O(1), /// where n - array length and p - number of increments. /// See <a href="https://en.wikipedia.org/wiki/Comb_sort">here</a> for more info. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { var gap = array.Length; var sorted = false; while (!sorted) { gap = (int)Math.Floor(gap / ShrinkFactor); if (gap <= 1) { gap = 1; sorted = true; } for (var i = 0; i < array.Length - gap; i++) { if (comparer.Compare(array[i], array[i + gap]) > 0) { (array[i], array[i + gap]) = (array[i + gap], array[i]); sorted = false; } } } } } }
53
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Cycle sort is an in-place, unstable sorting algorithm, /// a comparison sort that is theoretically optimal in terms of the total /// number of writes to the original array. /// It is based on the idea that the permutation to be sorted can be factored /// into cycles, which can individually be rotated to give a sorted result. /// </summary> /// <typeparam name="T">Type array input.</typeparam> public class CycleSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts input array using Cycle sort. /// </summary> /// <param name="array">Input array.</param> /// <param name="comparer">Integer comparer.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 0; i < array.Length - 1; i++) { MoveCycle(array, i, comparer); } } private static void MoveCycle(T[] array, int startingIndex, IComparer<T> comparer) { var item = array[startingIndex]; var pos = startingIndex + CountSmallerElements(array, startingIndex + 1, item, comparer); if (pos == startingIndex) { return; } pos = SkipSameElements(array, pos, item, comparer); var temp = array[pos]; array[pos] = item; item = temp; while (pos != startingIndex) { pos = startingIndex + CountSmallerElements(array, startingIndex + 1, item, comparer); pos = SkipSameElements(array, pos, item, comparer); temp = array[pos]; array[pos] = item; item = temp; } } private static int SkipSameElements(T[] array, int nextIndex, T item, IComparer<T> comparer) { while (comparer.Compare(array[nextIndex], item) == 0) { nextIndex++; } return nextIndex; } private static int CountSmallerElements(T[] array, int startingIndex, T element, IComparer<T> comparer) { var smallerElements = 0; for (var i = startingIndex; i < array.Length; i++) { if (comparer.Compare(array[i], element) < 0) { smallerElements++; } } return smallerElements; } } }
80
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements exchange sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class ExchangeSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// internal, in-place, stable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 0; i < array.Length - 1; i++) { for (var j = i + 1; j < array.Length; j++) { if (comparer.Compare(array[i], array[j]) > 0) { (array[j], array[i]) = (array[i], array[j]); } } } } } }
35
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Heap sort is a comparison based sorting technique /// based on Binary Heap data structure. /// </summary> /// <typeparam name="T">Input array type.</typeparam> public class HeapSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts input array using heap sort algorithm. /// </summary> /// <param name="array">Input array.</param> /// <param name="comparer">Comparer type for elements.</param> public void Sort(T[] array, IComparer<T> comparer) => HeapSort(array, comparer); private static void HeapSort(IList<T> data, IComparer<T> comparer) { var heapSize = data.Count; for (var p = (heapSize - 1) / 2; p >= 0; p--) { MakeHeap(data, heapSize, p, comparer); } for (var i = data.Count - 1; i > 0; i--) { var temp = data[i]; data[i] = data[0]; data[0] = temp; heapSize--; MakeHeap(data, heapSize, 0, comparer); } } private static void MakeHeap(IList<T> input, int heapSize, int index, IComparer<T> comparer) { var rIndex = index; while (true) { var left = (rIndex + 1) * 2 - 1; var right = (rIndex + 1) * 2; var largest = left < heapSize && comparer.Compare(input[left], input[rIndex]) == 1 ? left : rIndex; // finds the index of the largest if (right < heapSize && comparer.Compare(input[right], input[largest]) == 1) { largest = right; } if (largest == rIndex) { return; } // process of reheaping / swapping var temp = input[rIndex]; input[rIndex] = input[largest]; input[largest] = temp; rIndex = largest; } } } }
69
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Sorts array in ascending order using comparison sort. /// </summary> /// <typeparam name="T">Type of array item.</typeparam> public interface IComparisonSorter<T> { /// <summary> /// Sorts array in ascending order. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Comparer to compare items of <paramref name="array" />.</param> void Sort(T[] array, IComparer<T> comparer); } }
19
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements insertion sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class InsertionSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// internal, in-place, stable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 1; i < array.Length; i++) { for (var j = i; j > 0 && comparer.Compare(array[j], array[j - 1]) < 0; j--) { var temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } } }
34
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Sorts arrays using quicksort (selecting median of three as a pivot). /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public sealed class MedianOfThreeQuickSorter<T> : QuickSorter<T> { protected override T SelectPivot(T[] array, IComparer<T> comparer, int left, int right) { var leftPoint = array[left]; var middlePoint = array[left + (right - left) / 2]; var rightPoint = array[right]; return FindMedian(comparer, leftPoint, middlePoint, rightPoint); } private static T FindMedian(IComparer<T> comparer, T a, T b, T c) { if (comparer.Compare(a, b) <= 0) { // a <= b <= c if (comparer.Compare(b, c) <= 0) { return b; } // a <= c < b if (comparer.Compare(a, c) <= 0) { return c; } // c < a <= b return a; } // a > b >= c if (comparer.Compare(b, c) >= 0) { return b; } // a >= c > b if (comparer.Compare(a, c) >= 0) { return c; } // c > a > b return a; } } }
57
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; using System.Linq; namespace Algorithms.Sorters.Comparison { /// <summary> /// Divide and Conquer algorithm, which splits /// array in two halves, calls itself for the two /// halves and then merges the two sorted halves. /// </summary> /// <typeparam name="T">Type of array elements.</typeparam> public class MergeSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using merge sort algorithm, /// originally designed as external sorting algorithm, /// internal, stable, /// time complexity: O(n log(n)), /// space complexity: O(n), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Comparer to compare elements of <paramref name="array" />.</param> public void Sort(T[] array, IComparer<T> comparer) { if (array.Length <= 1) { return; } var (left, right) = Split(array); Sort(left, comparer); Sort(right, comparer); Merge(array, left, right, comparer); } private static void Merge(T[] array, T[] left, T[] right, IComparer<T> comparer) { var mainIndex = 0; var leftIndex = 0; var rightIndex = 0; while (leftIndex < left.Length && rightIndex < right.Length) { var compResult = comparer.Compare(left[leftIndex], right[rightIndex]); array[mainIndex++] = compResult <= 0 ? left[leftIndex++] : right[rightIndex++]; } while (leftIndex < left.Length) { array[mainIndex++] = left[leftIndex++]; } while (rightIndex < right.Length) { array[mainIndex++] = right[rightIndex++]; } } private static (T[] left, T[] right) Split(T[] array) { var mid = array.Length / 2; return (array.Take(mid).ToArray(), array.Skip(mid).ToArray()); } } }
67
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Sorts arrays using quicksort (selecting middle point as a pivot). /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public sealed class MiddlePointQuickSorter<T> : QuickSorter<T> { protected override T SelectPivot(T[] array, IComparer<T> comparer, int left, int right) => array[left + (right - left) / 2]; } }
15
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements pancake sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class PancakeSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// internal, in-place, stable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { var n = array.Length; // Start from the complete array and one by one // reduce current size by one for (var currSize = n; currSize > 1; --currSize) { // Find index of the maximum element in // array[0..curr_size-1] var mi = FindMax(array, currSize, comparer); // Move the maximum element to end of current array // if it's not already at the end if (mi != currSize - 1) { // To move to the end, first move maximum // number to beginning Flip(array, mi); // Now move the maximum number to end by // reversing current array Flip(array, currSize - 1); } } } // Reverses array[0..i] private void Flip(T[] array, int i) { T temp; var start = 0; while (start < i) { temp = array[start]; array[start] = array[i]; array[i] = temp; start++; i--; } } // Returns index of the maximum element // in array[0..n-1] private int FindMax(T[] array, int n, IComparer<T> comparer) { var mi = 0; for (var i = 0; i < n; i++) { if (comparer.Compare(array[i], array[mi]) == 1) { mi = i; } } return mi; } } }
79
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Sorts arrays using quicksort. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public abstract class QuickSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using Hoare partition scheme, /// internal, in-place, /// time complexity average: O(n log(n)), /// time complexity worst: O(n^2), /// space complexity: O(log(n)), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) => Sort(array, comparer, 0, array.Length - 1); protected abstract T SelectPivot(T[] array, IComparer<T> comparer, int left, int right); private void Sort(T[] array, IComparer<T> comparer, int left, int right) { if (left >= right) { return; } var p = Partition(array, comparer, left, right); Sort(array, comparer, left, p); Sort(array, comparer, p + 1, right); } private int Partition(T[] array, IComparer<T> comparer, int left, int right) { var pivot = SelectPivot(array, comparer, left, right); var nleft = left; var nright = right; while (true) { while (comparer.Compare(array[nleft], pivot) < 0) { nleft++; } while (comparer.Compare(array[nright], pivot) > 0) { nright--; } if (nleft >= nright) { return nright; } var t = array[nleft]; array[nleft] = array[nright]; array[nright] = t; nleft++; nright--; } } } }
69
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Sorts arrays using quicksort (selecting random point as a pivot). /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public sealed class RandomPivotQuickSorter<T> : QuickSorter<T> { private readonly Random random = new(); protected override T SelectPivot(T[] array, IComparer<T> comparer, int left, int right) => array[random.Next(left, right + 1)]; } }
18
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Class that implements selection sort algorithm. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class SelectionSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// internal, in-place, stable, /// time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var i = 0; i < array.Length - 1; i++) { var jmin = i; for (var j = i + 1; j < array.Length; j++) { if (comparer.Compare(array[jmin], array[j]) > 0) { jmin = j; } } var t = array[i]; array[i] = array[jmin]; array[jmin] = t; } } } }
40
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// TODO. /// </summary> /// <typeparam name="T">TODO. 2.</typeparam> public class ShellSorter<T> : IComparisonSorter<T> { /// <summary> /// Sorts array using specified comparer, /// based on bubble sort, /// internal, in-place, unstable, /// worst-case time complexity: O(n^2), /// space complexity: O(1), /// where n - array length. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { for (var step = array.Length / 2; step > 0; step /= 2) { for (var i = 0; i < step; i++) { GappedBubbleSort(array, comparer, i, step); } } } private static void GappedBubbleSort(T[] array, IComparer<T> comparer, int start, int step) { for (var j = start; j < array.Length - step; j += step) { var wasChanged = false; for (var k = start; k < array.Length - j - step; k += step) { if (comparer.Compare(array[k], array[k + step]) > 0) { var temp = array[k]; array[k] = array[k + step]; array[k + step] = temp; wasChanged = true; } } if (!wasChanged) { break; } } } } }
56
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.Comparison { /// <summary> /// Timsort is a hybrid stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. /// It was originally implemented by Tim Peters in 2002 for use in the Python programming language. /// /// This class is based on a Java interpretation of Tim Peter's original work. /// Java class is viewable here: /// http://cr.openjdk.java.net/~martin/webrevs/openjdk7/timsort/raw_files/new/src/share/classes/java/util/TimSort.java /// /// Tim Peters's list sort for Python, is described in detail here: /// http://svn.python.org/projects/python/trunk/Objects/listsort.txt /// /// Tim's C code may be found here: http://svn.python.org/projects/python/trunk/Objects/listobject.c /// /// The underlying techniques are described in this paper (and may have even earlier origins): /// "Optimistic Sorting and Information Theoretic Complexity" /// Peter McIlroy /// SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms), /// pp 467-474, Austin, Texas, 25-27 January 1993. /// </summary> /// <typeparam name="T">Type of array element.</typeparam> public class TimSorter<T> : IComparisonSorter<T> { private readonly int minMerge; private readonly int initMinGallop; private readonly int[] runBase; private readonly int[] runLengths; private int minGallop; private int stackSize; private IComparer<T> comparer = default!; /// <summary> /// Private class for handling gallop merges, allows for tracking array indexes and wins. /// </summary> /// <typeparam name="Tc">Type of array element.</typeparam> private class TimChunk<Tc> { public Tc[] Array { get; set; } = default!; public int Index { get; set; } public int Remaining { get; set; } public int Wins { get; set; } } public TimSorter(int minMerge = 32, int minGallop = 7) { initMinGallop = minGallop; this.minMerge = minMerge; runBase = new int[85]; runLengths = new int[85]; stackSize = 0; this.minGallop = minGallop; } /// <summary> /// Sorts array using specified comparer /// worst case performance: O(n log(n)), /// best case performance: O(n), /// See <a href="https://en.wikipedia.org/wiki/Timsort">here</a> for more info. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="comparer">Compares elements.</param> public void Sort(T[] array, IComparer<T> comparer) { this.comparer = comparer; var start = 0; var remaining = array.Length; if (remaining < minMerge) { if (remaining < 2) { // Arrays of size 0 or 1 are always sorted. return; } // Don't need to merge, just binary sort BinarySort(array, start, remaining, start); return; } var minRun = MinRunLength(remaining, minMerge); do { // Identify next run var runLen = CountRunAndMakeAscending(array, start); // If the run is too short extend to Min(MIN_RUN, remaining) if (runLen < minRun) { var force = Math.Min(minRun, remaining); BinarySort(array, start, start + force, start + runLen); runLen = force; } runBase[stackSize] = start; runLengths[stackSize] = runLen; stackSize++; MergeCollapse(array); start += runLen; remaining -= runLen; } while (remaining != 0); MergeForceCollapse(array); } /// <summary> /// Returns the minimum acceptable run length for an array of the specified /// length.Natural runs shorter than this will be extended. /// /// Computation is: /// If total less than minRun, return n (it's too small to bother with fancy stuff). /// Else if total is an exact power of 2, return minRun/2. /// Else return an int k, where <![CDATA[minRun/2 <= k <= minRun]]>, such that total/k /// is close to, but strictly less than, an exact power of 2. /// </summary> /// <param name="total">Total length remaining to sort.</param> /// <returns>Minimum run length to be merged.</returns> private static int MinRunLength(int total, int minRun) { var r = 0; while (total >= minRun) { r |= total & 1; total >>= 1; } return total + r; } /// <summary> /// Reverse the specified range of the specified array. /// </summary> /// <param name="array">the array in which a range is to be reversed.</param> /// <param name="start">the index of the first element in the range to be reversed.</param> /// <param name="end">the index after the last element in the range to be reversed.</param> private static void ReverseRange(T[] array, int start, int end) { end--; while (start < end) { var t = array[start]; array[start++] = array[end]; array[end--] = t; } } /// <summary> /// Left shift a value, preventing a roll over to negative numbers. /// </summary> /// <param name="shiftable">int value to left shift.</param> /// <returns>Left shifted value, bound to 2,147,483,647.</returns> private static int BoundLeftShift(int shiftable) => (shiftable << 1) < 0 ? (shiftable << 1) + 1 : int.MaxValue; /// <summary> /// Check the chunks before getting in to a merge to make sure there's something to actually do. /// </summary> /// <param name="left">TimChunk of the left hand side.</param> /// <param name="right">TimChunk of the right hand side.</param> /// <param name="dest">The current target point for the remaining values.</param> /// <returns>If a merge is required.</returns> private static bool NeedsMerge(TimChunk<T> left, TimChunk<T> right, ref int dest) { right.Array[dest++] = right.Array[right.Index++]; if (--right.Remaining == 0) { Array.Copy(left.Array, left.Index, right.Array, dest, left.Remaining); return false; } if (left.Remaining == 1) { Array.Copy(right.Array, right.Index, right.Array, dest, right.Remaining); right.Array[dest + right.Remaining] = left.Array[left.Index]; return false; } return true; } /// <summary> /// Moves over the last parts of the chunks. /// </summary> /// <param name="left">TimChunk of the left hand side.</param> /// <param name="right">TimChunk of the right hand side.</param> /// <param name="dest">The current target point for the remaining values.</param> private static void FinalizeMerge(TimChunk<T> left, TimChunk<T> right, int dest) { if (left.Remaining == 1) { Array.Copy(right.Array, right.Index, right.Array, dest, right.Remaining); right.Array[dest + right.Remaining] = left.Array[left.Index]; } else if (left.Remaining == 0) { throw new ArgumentException("Comparison method violates its general contract!"); } else { Array.Copy(left.Array, left.Index, right.Array, dest, left.Remaining); } } /// <summary> /// Returns the length of the run beginning at the specified position in /// the specified array and reverses the run if it is descending (ensuring /// that the run will always be ascending when the method returns). /// /// A run is the longest ascending sequence with: /// /// <![CDATA[a[lo] <= a[lo + 1] <= a[lo + 2] <= ...]]> /// /// or the longest descending sequence with: /// /// <![CDATA[a[lo] > a[lo + 1] > a[lo + 2] > ...]]> /// /// For its intended use in a stable mergesort, the strictness of the /// definition of "descending" is needed so that the call can safely /// reverse a descending sequence without violating stability. /// </summary> /// <param name="array">the array in which a run is to be counted and possibly reversed.</param> /// <param name="start">index of the first element in the run.</param> /// <returns>the length of the run beginning at the specified position in the specified array.</returns> private int CountRunAndMakeAscending(T[] array, int start) { var runHi = start + 1; if (runHi == array.Length) { return 1; } // Find end of run, and reverse range if descending if (comparer.Compare(array[runHi++], array[start]) < 0) { // Descending while (runHi < array.Length && comparer.Compare(array[runHi], array[runHi - 1]) < 0) { runHi++; } ReverseRange(array, start, runHi); } else { // Ascending while (runHi < array.Length && comparer.Compare(array[runHi], array[runHi - 1]) >= 0) { runHi++; } } return runHi - start; } /// <summary> /// Find the position in the array that a key should fit to the left of where it currently sits. /// </summary> /// <param name="array">Array to search.</param> /// <param name="key">Key to place in the array.</param> /// <param name="i">Base index for the key.</param> /// <param name="len">Length of the chunk to run through.</param> /// <param name="hint">Initial starting position to start from.</param> /// <returns>Offset for the key's location.</returns> private int GallopLeft(T[] array, T key, int i, int len, int hint) { var (offset, lastOfs) = comparer.Compare(key, array[i + hint]) > 0 ? RightRun(array, key, i, len, hint, 0) : LeftRun(array, key, i, hint, 1); return FinalOffset(array, key, i, offset, lastOfs, 1); } /// <summary> /// Find the position in the array that a key should fit to the right of where it currently sits. /// </summary> /// <param name="array">Array to search.</param> /// <param name="key">Key to place in the array.</param> /// <param name="i">Base index for the key.</param> /// <param name="len">Length of the chunk to run through.</param> /// <param name="hint">Initial starting position to start from.</param> /// <returns>Offset for the key's location.</returns> private int GallopRight(T[] array, T key, int i, int len, int hint) { var (offset, lastOfs) = comparer.Compare(key, array[i + hint]) < 0 ? LeftRun(array, key, i, hint, 0) : RightRun(array, key, i, len, hint, -1); return FinalOffset(array, key, i, offset, lastOfs, 0); } private (int offset, int lastOfs) LeftRun(T[] array, T key, int i, int hint, int lt) { var maxOfs = hint + 1; var (offset, tmp) = (1, 0); while (offset < maxOfs && comparer.Compare(key, array[i + hint - offset]) < lt) { tmp = offset; offset = BoundLeftShift(offset); } if (offset > maxOfs) { offset = maxOfs; } var lastOfs = hint - offset; offset = hint - tmp; return (offset, lastOfs); } private (int offset, int lastOfs) RightRun(T[] array, T key, int i, int len, int hint, int gt) { var (offset, lastOfs) = (1, 0); var maxOfs = len - hint; while (offset < maxOfs && comparer.Compare(key, array[i + hint + offset]) > gt) { lastOfs = offset; offset = BoundLeftShift(offset); } if (offset > maxOfs) { offset = maxOfs; } offset += hint; lastOfs += hint; return (offset, lastOfs); } private int FinalOffset(T[] array, T key, int i, int offset, int lastOfs, int lt) { lastOfs++; while (lastOfs < offset) { var m = lastOfs + (int)((uint)(offset - lastOfs) >> 1); if (comparer.Compare(key, array[i + m]) < lt) { offset = m; } else { lastOfs = m + 1; } } return offset; } /// <summary> /// Sorts the specified portion of the specified array using a binary /// insertion sort. It requires O(n log n) compares, but O(n^2) data movement. /// </summary> /// <param name="array">Array to sort.</param> /// <param name="start">The index of the first element in the range to be sorted.</param> /// <param name="end">The index after the last element in the range to be sorted.</param> /// <param name="first">The index of the first element in the range that is not already known to be sorted, must be between start and end.</param> private void BinarySort(T[] array, int start, int end, int first) { if (first >= end || first <= start) { first = start + 1; } for (; first < end; first++) { var target = array[first]; var targetInsertLocation = BinarySearch(array, start, first - 1, target); Array.Copy(array, targetInsertLocation, array, targetInsertLocation + 1, first - targetInsertLocation); array[targetInsertLocation] = target; } } private int BinarySearch(T[] array, int left, int right, T target) { while (left < right) { var mid = (left + right) >> 1; if (comparer.Compare(target, array[mid]) < 0) { right = mid; } else { left = mid + 1; } } return comparer.Compare(target, array[left]) < 0 ? left : left + 1; } private void MergeCollapse(T[] array) { while (stackSize > 1) { var n = stackSize - 2; if (n > 0 && runLengths[n - 1] <= runLengths[n] + runLengths[n + 1]) { if (runLengths[n - 1] < runLengths[n + 1]) { n--; } MergeAt(array, n); } else if (runLengths[n] <= runLengths[n + 1]) { MergeAt(array, n); } else { break; } } } private void MergeForceCollapse(T[] array) { while (stackSize > 1) { var n = stackSize - 2; if (n > 0 && runLengths[n - 1] < runLengths[n + 1]) { n--; } MergeAt(array, n); } } private void MergeAt(T[] array, int index) { var baseA = runBase[index]; var lenA = runLengths[index]; var baseB = runBase[index + 1]; var lenB = runLengths[index + 1]; runLengths[index] = lenA + lenB; if (index == stackSize - 3) { runBase[index + 1] = runBase[index + 2]; runLengths[index + 1] = runLengths[index + 2]; } stackSize--; var k = GallopRight(array, array[baseB], baseA, lenA, 0); baseA += k; lenA -= k; if (lenA <= 0) { return; } lenB = GallopLeft(array, array[baseA + lenA - 1], baseB, lenB, lenB - 1); if (lenB <= 0) { return; } Merge(array, baseA, lenA, baseB, lenB); } private void Merge(T[] array, int baseA, int lenA, int baseB, int lenB) { var endA = baseA + lenA; var dest = baseA; TimChunk<T> left = new() { Array = array[baseA..endA], Remaining = lenA, }; TimChunk<T> right = new() { Array = array, Index = baseB, Remaining = lenB, }; // Move first element of the right chunk and deal with degenerate cases. if (!TimSorter<T>.NeedsMerge(left, right, ref dest)) { // One of the chunks had 0-1 items in it, so no need to merge anything. return; } var gallop = minGallop; while (RunMerge(left, right, ref dest, ref gallop)) { // Penalize for leaving gallop mode gallop = gallop > 0 ? gallop + 2 : 2; } minGallop = gallop >= 1 ? gallop : 1; FinalizeMerge(left, right, dest); } private bool RunMerge(TimChunk<T> left, TimChunk<T> right, ref int dest, ref int gallop) { // Reset the number of times in row a run wins. left.Wins = 0; right.Wins = 0; // Run a stable merge sort until (if ever) one run starts winning consistently. if (StableMerge(left, right, ref dest, gallop)) { // Stable merge sort completed with no viable gallops, time to exit. return false; } // One run is winning so consistently that galloping may be a huge win. // So try that, and continue galloping until (if ever) neither run appears to be winning consistently anymore. do { if (GallopMerge(left, right, ref dest)) { // Galloped all the way to the end, merge is complete. return false; } // We had a bit of a run, so make it easier to get started again. gallop--; } while (left.Wins >= initMinGallop || right.Wins >= initMinGallop); return true; } private bool StableMerge(TimChunk<T> left, TimChunk<T> right, ref int dest, int gallop) { do { if (comparer.Compare(right.Array[right.Index], left.Array[left.Index]) < 0) { right.Array[dest++] = right.Array[right.Index++]; right.Wins++; left.Wins = 0; if (--right.Remaining == 0) { return true; } } else { right.Array[dest++] = left.Array[left.Index++]; left.Wins++; right.Wins = 0; if (--left.Remaining == 1) { return true; } } } while ((left.Wins | right.Wins) < gallop); return false; } private bool GallopMerge(TimChunk<T> left, TimChunk<T> right, ref int dest) { left.Wins = GallopRight(left.Array, right.Array[right.Index], left.Index, left.Remaining, 0); if (left.Wins != 0) { Array.Copy(left.Array, left.Index, right.Array, dest, left.Wins); dest += left.Wins; left.Index += left.Wins; left.Remaining -= left.Wins; if (left.Remaining <= 1) { return true; } } right.Array[dest++] = right.Array[right.Index++]; if (--right.Remaining == 0) { return true; } right.Wins = GallopLeft(right.Array, left.Array[left.Index], right.Index, right.Remaining, 0); if (right.Wins != 0) { Array.Copy(right.Array, right.Index, right.Array, dest, right.Wins); dest += right.Wins; right.Index += right.Wins; right.Remaining -= right.Wins; if (right.Remaining == 0) { return true; } } right.Array[dest++] = left.Array[left.Index++]; if (--left.Remaining == 1) { return true; } return false; } } }
635
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; namespace Algorithms.Sorters.External { public class ExternalMergeSorter<T> : IExternalSorter<T> { public void Sort( ISequentialStorage<T> mainMemory, ISequentialStorage<T> temporaryMemory, IComparer<T> comparer) { var originalSource = mainMemory; var source = mainMemory; var temp = temporaryMemory; var totalLength = mainMemory.Length; for (var stripLength = 1L; stripLength < totalLength; stripLength *= 2) { using var left = source.GetReader(); using var right = source.GetReader(); using var output = temp.GetWriter(); for (var i = 0L; i < stripLength; i++) { right.Read(); } Merge(left, right, output, stripLength, Math.Min(stripLength, totalLength - stripLength), comparer); var step = 2 * stripLength; long rightStripStart; for (rightStripStart = stripLength + step; rightStripStart < mainMemory.Length; rightStripStart += step) { for (var i = 0L; i < stripLength; i++) { left.Read(); right.Read(); } Merge( left, right, output, stripLength, Math.Min(stripLength, totalLength - rightStripStart), comparer); } for (var i = 0L; i < totalLength + stripLength - rightStripStart; i++) { output.Write(right.Read()); } (source, temp) = (temp, source); } if (source == originalSource) { return; } using var sorted = source.GetReader(); using var dest = originalSource.GetWriter(); for (var i = 0; i < totalLength; i++) { dest.Write(sorted.Read()); } } private static void Merge( ISequentialStorageReader<T> left, ISequentialStorageReader<T> right, ISequentialStorageWriter<T> output, long leftLength, long rightLength, IComparer<T> comparer) { var leftIndex = 0L; var rightIndex = 0L; var l = left.Read(); var r = right.Read(); while (true) { if (comparer.Compare(l, r) < 0) { output.Write(l); leftIndex++; if (leftIndex == leftLength) { break; } l = left.Read(); } else { output.Write(r); rightIndex++; if (rightIndex == rightLength) { break; } r = right.Read(); } } if (leftIndex < leftLength) { output.Write(l); Copy(left, output, leftLength - leftIndex - 1); } if (rightIndex < rightLength) { output.Write(r); Copy(right, output, rightLength - rightIndex - 1); } } private static void Copy(ISequentialStorageReader<T> from, ISequentialStorageWriter<T> to, long count) { for (var i = 0; i < count; i++) { to.Write(from.Read()); } } } }
130
C-Sharp
TheAlgorithms
C#
using System.Collections.Generic; namespace Algorithms.Sorters.External { public interface IExternalSorter<T> { /// <summary> /// Sorts elements in sequential storage in ascending order. /// </summary> /// <param name="mainMemory">Memory that contains array to sort and will contain the result.</param> /// <param name="temporaryMemory">Temporary memory for working purposes.</param> void Sort(ISequentialStorage<T> mainMemory, ISequentialStorage<T> temporaryMemory, IComparer<T> comparer); } }
15
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Sorters.External { public interface ISequentialStorage<T> { public int Length { get; } ISequentialStorageReader<T> GetReader(); ISequentialStorageWriter<T> GetWriter(); } }
12
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Sorters.External { public interface ISequentialStorageReader<out T> : IDisposable { T Read(); } }
10
C-Sharp
TheAlgorithms
C#
using System; namespace Algorithms.Sorters.External { public interface ISequentialStorageWriter<in T> : IDisposable { void Write(T value); } }
10
C-Sharp
TheAlgorithms
C#
using System.IO; namespace Algorithms.Sorters.External.Storages { public class IntFileStorage : ISequentialStorage<int> { private readonly string filename; public IntFileStorage(string filename, int length) { Length = length; this.filename = filename; } public int Length { get; } public ISequentialStorageReader<int> GetReader() => new FileReader(filename); public ISequentialStorageWriter<int> GetWriter() => new FileWriter(filename); private class FileReader : ISequentialStorageReader<int> { private readonly BinaryReader reader; public FileReader(string filename) => reader = new BinaryReader(File.OpenRead(filename)); public void Dispose() => reader.Dispose(); public int Read() => reader.ReadInt32(); } private class FileWriter : ISequentialStorageWriter<int> { private readonly BinaryWriter writer; public FileWriter(string filename) => writer = new BinaryWriter(File.OpenWrite(filename)); public void Write(int value) => writer.Write(value); public void Dispose() => writer.Dispose(); } } }
44
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Sorters.External.Storages { public class IntInMemoryStorage : ISequentialStorage<int> { private readonly int[] storage; public IntInMemoryStorage(int[] array) => storage = array; public int Length => storage.Length; public ISequentialStorageReader<int> GetReader() => new InMemoryReader(storage); public ISequentialStorageWriter<int> GetWriter() => new InMemoryWriter(storage); private class InMemoryReader : ISequentialStorageReader<int> { private readonly int[] storage; private int offset; public InMemoryReader(int[] storage) => this.storage = storage; public void Dispose() { // Nothing to dispose here } public int Read() => storage[offset++]; } private class InMemoryWriter : ISequentialStorageWriter<int> { private readonly int[] storage; private int offset; public InMemoryWriter(int[] storage) => this.storage = storage; public void Write(int value) => storage[offset++] = value; public void Dispose() { // Nothing to dispose here } } } }
46
C-Sharp
TheAlgorithms
C#
using System; using System.Collections.Generic; using System.Linq; namespace Algorithms.Sorters.Integer { /// <summary> /// Class that implements bucket sort algorithm. /// </summary> public class BucketSorter : IIntegerSorter { private const int NumOfDigitsInBase10 = 10; /// <summary> /// Sorts array elements using BucketSort Algorithm. /// </summary> /// <param name="array">Array to sort.</param> public void Sort(int[] array) { if (array.Length <= 1) { return; } // store maximum number of digits in numbers to sort var totalDigits = NumberOfDigits(array); // bucket array where numbers will be placed var buckets = new int[NumOfDigitsInBase10, array.Length + 1]; // go through all digit places and sort each number // according to digit place value for (var pass = 1; pass <= totalDigits; pass++) { DistributeElements(array, buckets, pass); // distribution pass CollectElements(array, buckets); // gathering pass if (pass != totalDigits) { EmptyBucket(buckets); // set size of buckets to 0 } } } /// <summary> /// Determines the number of digits in the largest number. /// </summary> /// <param name="array">Input array.</param> /// <returns>Number of digits.</returns> private static int NumberOfDigits(IEnumerable<int> array) => (int)Math.Floor(Math.Log10(array.Max()) + 1); /// <summary> /// To distribute elements into buckets based on specified digit. /// </summary> /// <param name="data">Input array.</param> /// <param name="buckets">Array of buckets.</param> /// <param name="digit">Digit.</param> private static void DistributeElements(IEnumerable<int> data, int[,] buckets, int digit) { // determine the divisor used to get specific digit var divisor = (int)Math.Pow(10, digit); foreach (var element in data) { // bucketNumber example for hundreds digit: // ( 1234 % 1000 ) / 100 --> 2 var bucketNumber = NumOfDigitsInBase10 * (element % divisor) / divisor; // retrieve value in pail[ bucketNumber , 0 ] to // determine the location in row to store element var elementNumber = ++buckets[bucketNumber, 0]; // location in bucket to place element buckets[bucketNumber, elementNumber] = element; } } /// <summary> /// Return elements to original array. /// </summary> /// <param name="data">Input array.</param> /// <param name="buckets">Array of buckets.</param> private static void CollectElements(IList<int> data, int[,] buckets) { var subscript = 0; // initialize location in data // loop over buckets for (var i = 0; i < NumOfDigitsInBase10; i++) { // loop over elements in each bucket for (var j = 1; j <= buckets[i, 0]; j++) { data[subscript++] = buckets[i, j]; // add element to array } } } /// <summary> /// Sets size of all buckets to zero. /// </summary> /// <param name="buckets">Array of buckets.</param> private static void EmptyBucket(int[,] buckets) { for (var i = 0; i < NumOfDigitsInBase10; i++) { buckets[i, 0] = 0; // set size of bucket to 0 } } } }
109
C-Sharp
TheAlgorithms
C#
using System; using System.Linq; namespace Algorithms.Sorters.Integer { /// <summary> /// Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that /// is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key /// value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. /// Its running time is linear in the number of items and the difference between the maximum and minimum key values, so /// it is only suitable for direct use in situations where the variation in keys is not significantly greater than the /// number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can /// handle larger keys more efficiently. /// </summary> public class CountingSorter : IIntegerSorter { /// <summary> /// <para> /// Sorts input array using counting sort algorithm. /// </para> /// <para> /// Time complexity: O(n+k), where k is the range of the non-negative key values. /// </para> /// <para> /// Space complexity: O(n+k), where k is the range of the non-negative key values. /// </para> /// </summary> /// <param name="array">Input array.</param> public void Sort(int[] array) { if (array.Length == 0) { return; } var max = array.Max(); var min = array.Min(); var count = new int[max - min + 1]; var output = new int[array.Length]; for (var i = 0; i < array.Length; i++) { count[array[i] - min]++; } for (var i = 1; i < count.Length; i++) { count[i] += count[i - 1]; } for (var i = array.Length - 1; i >= 0; i--) { output[count[array[i] - min] - 1] = array[i]; count[array[i] - min]--; } Array.Copy(output, array, array.Length); } } }
60
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Sorters.Integer { /// <summary> /// Sorts array of integers without comparing them. /// </summary> public interface IIntegerSorter { /// <summary> /// Sorts array in ascending order. /// </summary> /// <param name="array">Array to sort.</param> void Sort(int[] array); } }
15
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Sorters.Integer { /// <summary> /// Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the /// individual /// digits which share the same significant position and value. A positional notation is required, but because integers /// can represent /// strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not /// limited to integers. /// </summary> public class RadixSorter : IIntegerSorter { /// <summary> /// Sorts array in ascending order. /// </summary> /// <param name="array">Array to sort.</param> public void Sort(int[] array) { var bits = 4; var b = new int[array.Length]; var rshift = 0; for (var mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) { var cntarray = new int[1 << bits]; foreach (var t in array) { var key = (t & mask) >> rshift; ++cntarray[key]; } for (var i = 1; i < cntarray.Length; ++i) { cntarray[i] += cntarray[i - 1]; } for (var p = array.Length - 1; p >= 0; --p) { var key = (array[p] & mask) >> rshift; --cntarray[key]; b[cntarray[key]] = array[p]; } var temp = b; b = array; array = temp; } } } }
50
C-Sharp
TheAlgorithms
C#
namespace Algorithms.Sorters.String { /// <summary> /// Sorts array of strings without comparing them. /// </summary> public interface IStringSorter { /// <summary> /// Sorts array in ascending order. /// </summary> /// <param name="array">Array to sort.</param> void Sort(string[] array); } }
15