Skip to content

Instantly share code, notes, and snippets.

@fero23
Created October 18, 2023 18:42
Show Gist options
  • Save fero23/324a0d35406fa030d6a2296c6eef50bc to your computer and use it in GitHub Desktop.
Save fero23/324a0d35406fa030d6a2296c6eef50bc to your computer and use it in GitHub Desktop.
Combinatorics
namespace Scripts;
public class Combinatorics
{
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(List<T> input, int i = 0)
{
if (i >= input.Count - 1)
{
yield return input.ToList();
}
else
{
foreach (var permutation in GetPermutations(input, i + 1))
{
yield return permutation;
}
for (int j = i + 1; j < input.Count; ++j)
{
(input[i], input[j]) = (input[j], input[i]);
foreach (var permutation in GetPermutations(input, i + 1))
{
yield return permutation;
}
(input[i], input[j]) = (input[j], input[i]);
}
}
}
public static IEnumerable<IEnumerable<T>> GetCombinations<T>(List<T> input, int count = 0)
{
List<T> buffer = new(count);
foreach (var combination in GetCombinations(input, buffer, 0, count))
{
yield return combination;
}
}
private static IEnumerable<IEnumerable<T>> GetCombinations<T>(List<T> input, List<T> buffer, int offset, int count)
{
if (count == 0)
{
yield return buffer.ToList();
}
else
{
for (int i = offset; i <= input.Count - count; ++i)
{
buffer.Add(input[i]);
foreach (var combination in GetCombinations(input, buffer, i + 1, count - 1))
{
yield return combination;
}
buffer.RemoveAt(buffer.Count - 1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment