Search code examples
language-agnosticroman-numerals

Can this Roman Number to Integer converter code be shorter?


95 bytes currently in python

I,V,X,L,C,D,M,R,r=1,5,10,50,100,500,1000,vars(),lambda x:reduce(lambda T,x:T+R[x]-T%R[x]*2,x,0)

Here is the few test results, it should work for 1 to 3999 (assume input is valid char only)

>>> r("I")
1
>>> r("MCXI")
1111
>>> r("MMCCXXII")
2222
>>> r("MMMCCCXXXIII")
3333
>>> r("MMMDCCCLXXXVIII")
3888
>>> r("MMMCMXCIX")
3999

And this is not duplicate with this, this is reversed one.

So, is it possible to make that shorter in Python, or Other languages like ruby could be done shorter than that?


Solution

  • Shortest solutions from codegolf.com

    There was a "Roman to decimal" competition over at Code Golf some time ago. (Well, actually it's still running because they never end.) A Perl golfer by the name of eyepopslikeamosquito decided to win all four languages (Perl, PHP, Python, and Ruby), and so he did. He wrote a fascinating four-part series "The golf course looks great, my swing feels good, I like my chances" (part II, part III, part IV) describing his approaches over at Perl Monks.

    Here are his solutions:

    Ruby, 53 strokes

    n=1;$.+=n/2-n%n=10**(494254%C/9)%4999while C=getc;p$.
    

    Perl, 58 strokes

    $\+=$z-2*$z%($z=10**(19&654115/ord)%1645)for<>=~/./g;print
    

    He also has a 53-stroke solution, but it probably doesn't work right now: (it uses the $^T variable during a few second period in 2011!)

    $\+=$z-2*$z%($z=10**(7&$^T/ord)%1999)for<>=~/./g;print
    

    PHP, 70 strokes

    <?while(A<$c=fgetc(STDIN))$t+=$n-2*$n%$n=md5(o²Ûö¬Ñ.$c)%1858+1?><?=$t;
    

    The six weird characters in the md5(..) are chr(111).chr(178).chr(219).chr(246).chr(172).chr(209) in Perl notation.

    Python, 78 strokes

    t=p=0
    for r in raw_input():n=10**(205558%ord(r)%7)%9995;t+=n-2*p%n;p=n
    print t