using System.Collections.Generic;
using System.Diagnostics;
static readonly int[] _Numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
bool verifyResults = true;
RunSolution(Solution1, digits, sum, verifyResults);
void RunSolution(Func<int, int, bool, (int, List<int>)> solution, int digits, int sum, bool verifyResults) {
throw new InvalidOperationException("The value of sum is too high for the number of digits.");
Stopwatch stopWatch = new Stopwatch();
(int count, List<int> results) = solution(digits, sum, verifyResults);
Console.WriteLine($"Found {count} results in {stopWatch.Elapsed}");
Console.WriteLine($" Result: {string.Join(", ", results.Select(x => x.ToString("#,##0") + ":" + SumDigits(x)))}");
(int count, List<int> results) Solution1(int digits, int sum, bool returnResults) {
List<int> result = new List<int>();
int[][] combinationsWithRepetition = GetCombinationsWithRepetition(digits);
for (int i = 0; i < combinationsWithRepetition.Length; i++) {
int[] n = combinationsWithRepetition[i];
for (int j = 0; j < n.Length; j++) {
if (allAreEqual && d != n[0]) {
bool canReverse = allAreEqual == false && n[0] != 0;
result.Add(ConvertIntArrayToNumber(n, -1));
result.Add(ConvertIntArrayToNumber(n, 1));
result = result.OrderBy(x => x).ToList();
static int[][] GetCombinationsWithRepetition(int digits) {
if (digits == 1) return _Numbers.Select(t => new int[] { t }).ToArray();
return GetCombinationsWithRepetition(digits - 1)
.SelectMany(t => _Numbers.Where(o => o.CompareTo(t.Last()) >= 0),
(t1, t2) => t1.Concat(new int[] { t2 }).ToArray()).ToArray();
static int ConvertIntArrayToNumber(int[] input, int step) {
throw new InvalidOperationException("Input is cannot be null");
if (!(step == -1 || step == 1)) {
throw new InvalidOperationException("Step must 1 or -1");
for (int i = step < 0 ? input.Length - 1 : 0; step < 0 ? i >= 0 : i < input.Length; i += step) {
static int SumDigits(int input) {
string s = input.ToString();
for (int i = 0; i < s.Length; i++) {
result += Convert.ToInt32(c.ToString());