Created
May 15, 2018 06:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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