A collection of etudes, updated weekly, for the education and enjoyment of the savvy programmer
Your task is to write a program that lists all of the numbers from zero to one hundred, inclusive, in alphabetical order. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Pages: 1 2
As usual a Perl response… But this one has a Schwartzian transform – which makes the sort appreciably faster (although another approach can be memoization to cache the spellings). The transform adds an index to the sort {in this case the spelled out number}, sorts by the index and then removes it. It is a standard Perl technique to speed up these sorts of sorts.
Here’s a different way to solve the problem, by constructing a Finite State Automaton:
I can’t resist showing off that the Common Lisp format function can output integers in English.
@Jan: Other languages have libraries to do such things, eg. num2words in Python:
but where is the fun in that?
I was needlessly verbose there:
I’m disappointed that num2words doesn’t seem to support Catalan.
In Python for numbers in dutch (the language was not specified in this exercise). The rules for dutch number spelling are a little more complicated than for english number spelling.
@Paul: nice. How are you getting the right sorting order for the Dutch? Locale setting?
Or ICU works nicely:
@matthew: I did not really think about the sorting order in the Dutch language. I should have done that, of course. The official Dutch alphabet ordering is like string.ascii_lower. The characters é and ë are supposed to be the same as e for ordering. That results in the order that you gave in your last post.
Here’s a solution in Python.
Output: