public static void Main(string[] args) { while (true) { Console.WriteLine("--------------"); Alphametik alphametik = ReadAlphametik(); if (alphametik == null) { continue; } try { SortedList <char, int> assignment = alphametik.Solve(); if (assignment == null) { Console.WriteLine("There is no solution for this alphametik."); } else { PrintAssignment(alphametik, assignment); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public SortedList <char, int> Solve() { if (this.SymbolTable.Count > 10) { throw new Exception("Too many letters."); } SortedList <char, int> assignment = new SortedList <char, int>(); switch (this.Operator) { case Operator.Addition: if (this.Result.Length == this.MaximumWordLength + 1) { assignment[this.Result[0]] = 1; // this HAS to be 1, for mathematical background see documentation } else if (this.Result.Length != this.MaximumWordLength) { throw new Exception("The result has to few or to many letters."); } break; case Operator.Multiplication: int wordSum = this.Words.Sum((s) => s.Length); if (this.Result.Length != wordSum) // as every word has to start with non-zero the result must be of that length { throw new Exception("The result has to few or to many letters."); } break; case Operator.Subtraction: // change alphametik to get same results solving a additive/multiplicative alphametik case Operator.Division: { string[] newWords = new string[this.Words.Length]; Array.Copy(this.Words, newWords, this.Words.Length); newWords[0] = this.Result; Alphametik alphametik = new Alphametik(this.Words[0], (Operator)((int)this.Operator - 1), newWords); return(alphametik.Solve()); } } // Start recursive search for solutions if (SearchRecursive(0, 0, assignment, 0)) { return(assignment); } else { return(null); } }
private static void PrintAssignment(Alphametik alphametik, SortedList <char, int> assignment) { Console.WriteLine("The following assinment solves the alphametik: "); assignment.All(kvp => { Console.WriteLine("{0} -> {1}", kvp.Key, kvp.Value); return(true); }); string op = ""; switch (alphametik.Operator) { case Operator.Addition: op = "+"; break; case Operator.Subtraction: op = "-"; break; case Operator.Multiplication: op = "*"; break; case Operator.Division: op = "/"; break; } Console.Write(String.Join(" " + op + " ", alphametik.Words.Select((w) => Alphametik.Convert(w, assignment)))); Console.WriteLine(" = {0}", Alphametik.Convert(alphametik.Result, assignment)); }