From: Rob Biedenharn Date: 2009-11-11T22:35:51+09:00 Subject: Re: Roman Numerals (Arrgh!) On Nov 10, 2009, at 10:30 PM, Gennady Bystritsky wrote: > On Nov 10, 2009, at 6:43 PM, Rob Biedenharn wrote: >> On Nov 10, 2009, at 8:49 PM, Gennady Bystritsky wrote: >>> On Nov 10, 2009, at 5:37 PM, Rob Biedenharn wrote: >>>> On Nov 10, 2009, at 6:56 PM, Rick Barrett wrote: >>>>> I have a homework assignment where I have to convert an inputted >>>>> integer >>>>> into Roman Numerals. I was doing fine building upon the previous >>>>> steps >>>> >>>> P.S. I saw Gennady's post, but I'd argue that no one would really >>>> want >>>> to solve the problem that way. And Nik's way doesn't give any help >>> >>> Why not that way? It works and it is short ;-) >>> >>> Gennady. >> >> Not that it doesn't work, just that it might be easier/quicker to >> rewrite than to understand. Short isn't *always* a virtue and if >> there's a reason (performance?) to be terse, then there ought to be a >> comment by way of explanation. >> >> There are few truly necessary uses of Enumerable#inject and this >> isn't > > I respectfully disagree. inject() is a very powerful facility that > allows quick elegant implementation of many tasks at hand. I usually > start with an inject()-based implementation (where appropriate) and > then may refactor it later if performance is not satisfactory. The > latter does not happen very often, though. As for the virtue, the > less code you write the fewer bugs get in -- especially when you use > well tested standard facilities like inject(). Well, I won't argue the fact that inject is a powerful abstraction. I *will* argue that it would be much easier to inject a bug (pun intended ;-) into your original terse code than something that is a bit longer, but tries to do less at each step. Changing/swapping array subscripts, for example. > >> one of them, but if it were, I'd make it at least slightly more >> readable: >> >> def roman_numeral(number) >> $numerals.inject(["", number]) { |(answer, number), (arabic, >> roman)| > > For that thanks a lot -- somehow I missed the fact it is possible in > ruby. > >> [ answer + roman * (number / arabic), number % arabic ] >> }.first >> end >> >> And with an appropriately formed $numerals array, the "subtraction >> rule" is already covered. ;-) > > Would you please elaborate? You mean same algorithm and "better" > $numerals would cover mapping of 4 => "IV", 9 => "IX", etc.? > >> >> -Rob Yes, that's it exactly. Testing/using 9 before 5, you find IX (and stop) before you go to VIIII. You can't repeat one of the "subtraction groups" the way that you can repeat the individual numerals: 8 is always VIII and never IVIV or IIX Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com