Alphametic Solver in C
By user12607856 on Feb 13, 2008
I decided to see if there were any freely available programs around to solve this type of puzzle.
There is a nice online solver by Truman Collins which looks like it's been there for at least 10 years.
I also found a version in C written a couple of years ago by Anuj Prateek and Upendra Singh.
(Update: The alphametic puzzle solver is not written by Prateek and Singh. The original code is by Naoyuki Tamura. See this post (and its comments) for more details.)
At the moment, it just does alphametic addition problems. If I had to guess, I'd say this was one of their first C programs and possibly done because of school work. The formatting and indentation was lousy and there were a load of things that newcomers to C do (such as returns at the end of functions when they aren't needed and two printf statements where one would do). But Burridge's Rules of Programming are:
- Get it working.
- Get it better.
- Get it faster/smaller.
and they've already done #1 so this wasn't a big deal.
But to try to understand it, I decided to tidy it up. I made the following changes:
- Changed the program name from "crypt" to "alphametic". There is already a "crypt" program on my machine.
- Added a bunch of newlines, consistent formatting and four space indentation to make the code more readable.
- Removed all Tabs. Repeat after me, tabs are evil.
- Included the .h file contents in the single .c source file.
- Included the README file contents in the single .c source file.
- Removed the Makefile and added a comment at the top to tell people how to do a simple compile.
- Rearranged the order of the various routines so that function prototypes aren't needed.
- Removed #include lines that weren't needed.
- Adjusted so that there was a single statement per line.
- Removed the useless calls to "system("cls") and the initial bogus gets call.
- Adjusted the initial message that's displayed, to add the line:
"\\nTYPE 'HELP' FOR HELP\\n".
- Added a simple "> " prompt at the start of each line where the program wants input, so you at least have an idea that you are required to enter something.
The new self-contained single source file is here. There are lots of other places where the code could be improved (like adding comments and better string handling), but I stopped there.
After looking at this, I'm convinced that it's just crying out to be converted to something like Python. The setjmp/longjmp code would naturally become try/except clauses and raising an exception. Some of the other routines that are several lines long would be simple one-liners in Python.
Hopefully I'll have some more time soon to try this, and also expand it so that it solves other alphametic puzzles apart from addition.