Roman Numeral Line Segments

C, 148 129 chars

d,x,n[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,4,5,2,3,1,3,2,4,2,3,2,3,1};f(c){while(d+=(c/n[x])*n[x+13],c%=n[x++]);return d;}

My first code-golf :^). Since the question states I can use a function, I have changed main to a function to trim some chars (most importantly: pass c as parameter rather scanf)

unpacked

d,x,n[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,4,5,2,3,1,3,2,4,2,3,2,3,1};
f(c){
  while(d+=(c/n[x])*n[x+13],
        c%=n[x++]);
  return d;
}

Mathematica, 80 72 bytes

Tr[Characters[#~IntegerString~"Roman"]/.{"I"|"C"->1,"M"->4,_String->2}]&

Anonymous function that just converts numbers to Roman numerals, replaces each character with its number of segments, and takes the total.


Pyth, 92 76 70 bytes

KsMc."/9hæ²z³Þ§ªW×Oû[Tnè,O¤"\/WQ=Q-Q=Nef!>TQ%2K aY@KhxKN;sY

Try it here!

Thanks to @FryAmTheEggman for some string packing suggestions which saved me some bytes!

I am still wondering if there is a mathematical way of encoding this list. Will try to figure something out.

Explanation

This uses the given algorithm. K contains the given list with the numbers and the corrosponding number of line segments in alternation. This list gets constructed by splitting a packed string, which gets decoded to 0/0/1/1/4/3/5/2/9/3/10/2/40/4/50/2/90/3/100/1/400/3/500/2/900/5/1000/4, on / and mapping each element to an integer.

KsMc."..."\/WQ=Q-Q=Nef!>TQ%2K aY@KhxKN;sY    # Q = input

   c."..."\/                                 # split the string on /
KsM                                          # map every number to int and assign to K
            WQ                               # while Q != 0
                     f    %2K                # only take every 2nd element of K and filter with T
                      !>TQ                   # T <= Q
                  =Ne                        # Take the last element of that and assign that to N
              =Q-Q                           # Q = Q - N
                                   xKN       # index of the first occurence of N in K
                                  h          # increment that index because we want the line segments
                              aA@K           # get the line segment from that index and append that to Y
                                      ;sY    # end the loop and print the sum of all line segments in Y

Tags:

Code Golf