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 T-SQL (SQL Server 2005) function, including test cases:
I can't find the file now, but this was an Intro to Programming problem (late in the term) where I went to school. We had to be able to turn a float into a valid written number for use on a check.
After the assignment was completed the professor showed some C++ code that solved the problem using only concepts we'd already covered. It ran just 43 lines, and was well-documented.
Does anyone plan on adding the appropriate commas and 'and' any time soon? Or hyphenating twenty-one through ninety-nine? Not much point otherwise, IMHO :)
'Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine'
vs
'Nine hundred and ninety-nine thousand, nine hundred and ninety-nine'
(And no, mine doesn't work. Yet.)
Is this cheating?
Here's a Scala solution. I'm not happy about trying to make it look short -- I sacrificed a bit of readability :(
Usage is:
Python, 446 bytes. All lines under 80 columns, dammit. This is Paul Fisher's solution with coding tweaks on almost every line, down from his 488-byte version; he's since squeezed out several more bytes, and I concede. Go vote for his answer!
The history has gotten complicated. I started with the unobfuscated code below, which supports negative numbers and range-checking, plus dashes in some numbers for better English:
Then I squeezed it to about 540 bytes via obfuscation (new to me), and Paul Fisher found a shorter algorithm (dropping the dashes) along with some marvelously horrible Python coding tricks. I stole the coding tricks to get down to 508 (which still did not win). I tried restarting fresh with a new algorithm, which was unable to beat Fisher's. Finally here's the tweak of his code. Respect!
The obfuscated code has been tested against the clean code, which was checked by eyeball on a bunch of cases.