The code golf series seem to be fairly popular. I ran across some code that converts a number to its word representation. Some examples would be (powers of 2 for programming fun):
- 2 -> Two
- 1024 -> One Thousand Twenty Four
- 1048576 -> One Million Forty Eight Thousand Five Hundred Seventy Six
The algorithm my co-worker came up was almost two hundred lines long. Seems like there would be a more concise way to do it.
Current guidelines:
- Submissions in any programming language welcome (I apologize to PhiLho for the initial lack of clarity on this one)
- Max input of 2^64 (see following link for words, thanks mmeyers)
- Short scale with English output preferred, but any algorithm is welcome. Just comment along with the programming language as to the method used.
A few years ago I created this in C# for multi language applications.
This one is base class:
This one is for wordify..
And this one is for Turkish Lera (TRY):
And it is used this way:
Ok, I think it's time for my own implementation in Windows BATCH script (should work on Windows 2000 or later).
Here is the code:
This is the test script I used:
And this is the output I got from my test script:
If I could find some more names of large numbers, the script would support even bigger numbers. Currently, though, the script will work with all numbers from -(10^66-1) to (10^66-1).
I have to mention, that I had a lot of fun solving this in BATCH. :)
In A86 assember - assembles to a .COM executable:
That's a 454 byte executable.
Here's the (slightly smaller) code. Since A86 is an 8086 only assembler, I've had to hand code the 32bit extensions:
The text is stored using Huffman encoding. The command line is passed as a string so converting it is simple - split the string into groups of three and parse each group (hundreds, tens and units) following each with the current multiplier (millions, thousands, etc).
Ok, here's F#, trying to stay readable, at about 830 bytes:
and here are the unit tests
Lisp, using only standard functions:
Bonus:
C# - 30 lines incl. method declaration and { }s:
Takes into account all the previously aforementioned commas, ands and hyphens. I've only included up to octillion because decimal.MaxValue is only in the octillions. For bigger integers you would need to add corresponding items to the thou[] array and perhaps pass the number in as a string, modifying the line to extract the block by using the last 3 chars instead of using modulo as I have here.
Called using:
Output: