private static Expression Solve(ProblemStatement problem) { Queue <Expression> combining = new Queue <Expression>( problem.InputNumbers.Select(number => new Expression(number))); List <Expression> known = new List <Expression>(); while (combining.TryDequeue(out Expression current)) { if (current.Value == problem.DesiredResult) { return(current); } IEnumerable <Expression> combinableWith = known.Where( expr => !expr.UsedNumbers.Intersect(current.UsedNumbers).Any()).ToList(); foreach (Expression existing in combinableWith) { combining.Enqueue( current.CombineWith(existing, '+', current.Value + existing.Value)); } known.Add(current); } return(null); }
static void Main(string[] args) { while (true) { ProblemStatement problem = ReadProblem(); if (problem == null) { break; } Expression solution = Solve(problem); string report = solution?.ToString() ?? "No solution found."; Console.WriteLine(report); Console.WriteLine(); } }