George said:
I'd love to know how some of the heavy hitters here
would program this.
I don't know whether I count as a heavy hitter, but my reply is that I wouldn't
program this. The trivial reason is that its a totally unrealistic exercise,
and I feel no need to mess with such. The more important reason is that it's
underspecified in several ways.
One -- as you have already mentioned -- is that the spec doesn't, um, specify
what to do with repetitions.
Another is that the special-casing of zero sounds suspicious to me -- zero is
even in my book. As a professional programmer I'd want to go back to the
"customer" (or analyst if there was one, and s/he struck me as competent) to
check that they really understood what they were calling for.
A third is that the spec seems to call for the input being an integer, not a
String as most people have assumed in their replies. An integer has many
natural representations, none of which are implicit in the value itself. E.g.
these all represent the same integer:
0x00010
0x10
16
000016
How many '0's are there ? (And should 'x's be counted ?) What about negative
numbers ? OTOH, if the input /is/ a String, how are non-digit characters to
be handled ? Can the String be in hex format ? Is the String representing
real Unicode, or can I assume there's a one-to-one mapping between Java 'char's
and actual characters ? Should I allow non-Western representations of numbers
?
The next problem is that I don't know the context where the code is going to be
used (and I can't make a reasonable guess either, because the problems is so
artificial). Is it going to be in the tightest part of the inner loop of an
interpreter that will run the whole application ? Is it just going to be run
once or twice a year as part of an error-reporting routine. Somewhere
in-between ? I don't know whether to optimise the code for clarity or
speed -- or, more accurately, I don't have the information to give good weights
to those potential virtues (either /could/ be zero).
Lastly, even treating it as an exercise, I don't know what I'm supposed to be
demonstrating my knowledge of. Should I just create a nasty little C-style
static method containing a loop, or should I demonstrate real OO, and create a
DigitsCount class, with responsibility for performing the calculation, and
holding the results ? Should I design that class in XP style (YAGNI, and that)
so that it /only/ accepted a String to decode and /only worked in decimal, or
should I approach it in library programmer style, and attempt to cover all the
legitimate uses of the object (e.g. accepting text streams and CharSequences as
sources of the data to analyse, and having an optional 'base' parameter) ?
I'd be interested to hear of any other reasons for refusing the assignment ;-)
I /think/ I've covered the bases, but I suspect I can be proved wrong....
-- chris