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.
Perl & CPAN working together:
Here's a relatively straightforward implementation in C (52 lines).
NOTE: this does not perform any bounds checking; the caller must ensure that the calling buffer is large enough.
And here's a much more obfuscated version of that (682 characters). It could probably be pared down a little more if I really tried.
Perl 5.10
Notes:
split()
that seems to be the main problem. As it sits now the strings take up the bulk of the characters.my
's, and thelocal
, as well as putting it all on one line.strict
andwarnings
.Mmm, you might have put the bar a bit high, both on the limit (18,446,744,073,709,552,000, I don't even know how to write that!) and on the goal (the other code golfs resulted in short code, this one will be long at least for the data (words)).
Anyway, for the record, I give an well known solution (not mine!) for French, in PHP: Écriture des nombres en français. :-)
Note the ambiguity (voluntary or not) of your wording: "Submissions in any language welcome"
I first took it as "natural language", before understand you probably meant "programming language...
The algorithm is probably simpler in English (and with less regional variants...).
Paul Fischer and Darius: You guys have some great ideas, but I hate to see them implemented in such an overly verbose fashion. :) Just kidding, your solution is awesome, but I squeezed
1430 more bytes out, while staying inside of 79 columns and maintaining python 3 compatibility.So here's my 416 byte python within 79 columns: (thanks guys, I'm standing on your shoulders)
And the tests:
In the D programming language
Try it out here