Skip to content

Instantly share code, notes, and snippets.

@Jyosua
Created May 15, 2018 06:00
Show Gist options
  • Save Jyosua/5b39531f1955aec0bcfe88db35d7f469 to your computer and use it in GitHub Desktop.
Save Jyosua/5b39531f1955aec0bcfe88db35d7f469 to your computer and use it in GitHub Desktop.
Just some basic C# code for generating unique combinations from 1 to N
using System;
using System.Collections.Generic;
using System.Linq;
namespace StudyCode
{
public static class Combination
{
public static List<int[]> Combinations(HashSet<int> availableNumbers, int[] currentArray, int index)
{
var result = new List<int[]>();
if(availableNumbers.Count == 0)
result.Add(currentArray);
foreach(var number in availableNumbers)
{
var newArray = new int[currentArray.Length];
currentArray.CopyTo(newArray, 0);
var remaining = new HashSet<int>(availableNumbers);
remaining.Remove(number);
newArray[index] = number;
result.AddRange(Combinations(remaining, newArray, index + 1));
}
return result;
}
public static List<int[]> CombinationsFor(int n) {
return Combinations(new HashSet<int>(Enumerable.Range(1, n)), new int[n], 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment