Skip to content

Instantly share code, notes, and snippets.

@pjsvis
Last active July 13, 2020 19:21
Show Gist options
  • Save pjsvis/2298311540f59993b838 to your computer and use it in GitHub Desktop.
Save pjsvis/2298311540f59993b838 to your computer and use it in GitHub Desktop.
IEnumerable<IEnumerable<int>> GenerateCage(int num, int target, params int[] excluded)
{
return GenerateCageInner(num, target, 1, 9, new HashSet<int>(excluded));
}
private IEnumerable<IEnumerable<int>> GenerateCageInner(int num, int target, int min, int max, HashSet<int> excluded)
{
// Base case
if (num == 0)
{
if (target == 0) yield return new int[0];
yield break;
}
// Recursive case
for (int i = min; i <= max && i <= target; i++)
{
if (excluded.Contains(i)) continue;
foreach (var subsoln in GenerateCageInner(num - 1, target - 1, min + 1, max, excluded))
{
var soln = new List<int>();
soln.Add(i);
soln.AddRange(subsoln);
yield return soln;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment