Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Coding Challenge Of The Day

Coding Challenge Of The Day

Scheduled Pinned Locked Moved The Lounge
c++architecture
51 Posts 30 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W wizardzz

    I didn't see you award him any points. Go on, 5 him!

    S Offline
    S Offline
    S Houghtelin
    wrote on last edited by
    #16

    Thanks wizardzz, I suppose he meant like virtual points, or maybe pints, I'll definitely takes pints! :-D

    It was broke, so I fixed it.

    1 Reply Last reply
    0
    • C Chris Maunder

      Actually it's a personality test to see who among you are worthy of being labelled a Brogrammer.

      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

      B Offline
      B Offline
      Bassam Abdul Baki
      wrote on last edited by
      #17

      You may want to snag CodeBroject.com just in case (CodePreject.com too).

      Web - BM - RSS - Math - LinkedIn

      1 Reply Last reply
      0
      • C Chris Maunder

        Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

        S Offline
        S Offline
        Sentenryu
        wrote on last edited by
        #18

        as a nerd, i can't resist... between, it's only a quick n' dirty solution:

        public static int RomanToArabic(string romans) {
        if (string.IsNullOrWhiteSpace(romans))
        {
        return 0;
        }
        //remove whitespace...
        romans = romans.Replace(" ", string.Empty);
        //make sure no one pass out an "A" for example...
        if (!Regex.IsMatch(romans, "(I|V|X|C|M|D|L)+"))
        {
        throw new ArgumentException("Invalid numeral!!");
        }

                //actual validation that matters (based on http://en.wikipedia.org/wiki/Roman\_numerals): 
                //The symbols "I", "X", "C", and "M" can be repeated three times in succession, but no more. "D", "L", and "V" can never be repeated.
                string invalidSequences = "(XXXX+)|(IIII+)|(CCCC+)|(MMMM+)|(DD+)|(LL+)|(VV+)";
        
                if (Regex.IsMatch(romans, invalidSequences))
                {
                    throw new ArgumentException("Invalid sequence!!");
                }
        
                int result = 0;
        
                result += Regex.Matches(romans, "IV").Count \* 4;
                romans = Regex.Replace(romans, "IV", string.Empty);
        
                result += Regex.Matches(romans, "IX").Count \* 9;
                romans = Regex.Replace(romans, "IX", string.Empty);
        
                result += Regex.Matches(romans, "XL").Count \* 40;
                romans = Regex.Replace(romans, "XL", string.Empty);
        
                result += Regex.Matches(romans, "XC").Count \* 90;
                romans = Regex.Replace(romans, "XC", string.Empty);
        
                result += Regex.Matches(romans, "CD").Count \* 400;
                romans = Regex.Replace(romans, "CD", string.Empty);
        
                result += Regex.Matches(romans, "CM").Count \* 900;
                romans = Regex.Replace(romans, "CM", string.Empty);
        
                result += romans.Count(x => x == 'I');
                romans = romans.Replace("I", string.Empty);
        
                result += romans.Count(x => x == 'V') \* 5;
                romans = romans.Replace("V", string.Empty);
        
                result += romans.Count(x => x == 'X') \* 10;
                romans = romans.Replace("X", string.Empty);
        
                result += romans.Count(x => x == 'L') \* 50;
                romans = romans.Replace("L", string.Empty);
        
                result += romans.Count(x => x == 'C') \* 100;
                romans = romans.Replace("C", string.Empty);
        
                result += romans.Count(x => x == 'D') \* 500;
                romans = romans.Replace("D", strin
        
        1 Reply Last reply
        0
        • C Chris Maunder

          You get points for at least writing code. As opposed to some members... (dark looks all 'round).

          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

          S Offline
          S Offline
          S Houghtelin
          wrote on last edited by
          #19

          Just like positive reenforcment in the schools today, everybody gets a trophy, even when they're wrong. Thanks! :thumbsup: :-D

          It was broke, so I fixed it.

          1 Reply Last reply
          0
          • S Steve Mayfield

            Don't you mean 'V' him?

            Steve _________________ I C(++) therefore I am

            A Offline
            A Offline
            AspDotNetDev
            wrote on last edited by
            #20

            Good catch. Live long and prosper.

            Thou mewling ill-breeding pignut!

            1 Reply Last reply
            0
            • C Chris Maunder

              Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

              K Offline
              K Offline
              Karl Sanford
              wrote on last edited by
              #21

              Chris Maunder wrote:

              Roman numerals to Arabic numbers

              totally read this backward... at least now I have a solution for Arabic to Roman Numerals :doh:

              Be The Noise

              1 Reply Last reply
              0
              • C Chris Maunder

                Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #22

                #!/usr/bin/python

                import sys

                I=1
                V=5
                X=10
                L=50
                C=100
                D=500
                M=1000

                a=0
                b=0
                c=0

                for d in map(eval,sys.argv[1]):
                if d > a:
                b += d - c
                c = 0
                else:
                b += c
                c = d
                a = d
                print b + c

                L 1 Reply Last reply
                0
                • J Joan M

                  Chris... you should know that we don't make homework here... :rolleyes:

                  [www.tamautomation.com] Robots, CNC and PLC machines for grinding and polishing.

                  C Offline
                  C Offline
                  Corporal Agarn
                  wrote on last edited by
                  #23

                  Tried to leave a similar message earlier but CP locked. I was going to add this is not QA. :)

                  1 Reply Last reply
                  0
                  • C Chris Maunder

                    Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                    J Offline
                    J Offline
                    jesarg
                    wrote on last edited by
                    #24

                    private int ToInt(string rom)
                    {
                    int length = rom.Length;
                    int result = 0;
                    for(int loop1=0; loop1 < length; loop1++)
                    {
                    char current = rom[loop1];
                    char next = loop1 < length - 1 ? rom[loop1 + 1] : ' ';
                    switch(current)
                    {
                    case 'I':
                    result += next == 'V' || next == 'X' ? -1 : 1;
                    break;
                    case 'V':
                    result += 5;
                    break;
                    case 'X':
                    result += next == 'L' || next == 'C' ? -10 : 10;
                    break;
                    case 'L':
                    result += 50;
                    break;
                    case 'C':
                    result += next == 'D' || next == 'M' ? -100 : 100;
                    break;
                    case 'D':
                    result += 500;
                    break;
                    case 'M':
                    result += 1000;
                    break;
                    }
                    }
                    return result;
                    }

                    1 Reply Last reply
                    0
                    • L Lost User

                      #!/usr/bin/python

                      import sys

                      I=1
                      V=5
                      X=10
                      L=50
                      C=100
                      D=500
                      M=1000

                      a=0
                      b=0
                      c=0

                      for d in map(eval,sys.argv[1]):
                      if d > a:
                      b += d - c
                      c = 0
                      else:
                      b += c
                      c = d
                      a = d
                      print b + c

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #25

                      Or, somewhat more tersely,

                      def r2d3(r,(s,M,C,X,I,z,V,L,D)=["%%s%d"%v for v in[1001,1000,100,10,1,0,5,50,500]]):
                      return eval("".join([
                      p%"+-"[eval( p%"%s>"%d%"")]
                      for d,p in zip(map(eval,'%sz'%r),map(eval,'s%s'%r))
                      ][1:]))

                      Y 1 Reply Last reply
                      0
                      • C Chris Meech

                        I once met a well formed roman, when I was touring through Italy. :cool:

                        Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra] posting about Crystal Reports here is like discussing gay marriage on a catholic church’s website.[Nishant Sivakumar]

                        L Offline
                        L Offline
                        Luc Pattyn
                        wrote on last edited by
                        #26

                        that would be where most Romans are, don't you think? :)

                        Luc Pattyn [My Articles] Nil Volentibus Arduum

                        1 Reply Last reply
                        0
                        • C Chris Maunder

                          Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                          L Offline
                          L Offline
                          Luc Pattyn
                          wrote on last edited by
                          #27

                          no arrays, no dictionaries, no obscure language, just some original coding:

                          public static bool TryParseRoman(string wellFormedRoman, out int val) {
                          val=0;
                          int prevDigit=0;
                          foreach (char c in wellFormedRoman) {
                          int index="IVXLCDM".IndexOf(c);
                          if (index<0) {val=0; return false;}
                          int digit=1;
                          int factor=5;
                          while (--index>=0) { digit*=factor; factor=7-factor; }
                          if (prevDigit

                          BTW: is it Friday already?

                          :)

                          Luc Pattyn [My Articles] Nil Volentibus Arduum

                          P 1 Reply Last reply
                          0
                          • C Chris Maunder

                            Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #28

                            I'm unsure when I wrote this, but it must have been the 90s, in VAX C or DEC C. I'm shocked (shocked! I say) at the inconsistent braces. :wtf:

                            size_t
                            roman2dec
                            (
                            char *subject
                            )
                            {
                            size_t result = 0 , current , high = 0 ;
                            int index ;

                            for ( index = strlen(subject)-1 ; index >= 0 ; index-- ) {
                                switch ( (char) \*(subject + index) )
                                {
                                    case 'I' :
                                    case 'i' : current =    1 ; break ;
                            
                                    case 'V' :
                                    case 'v' : current =    5 ; break ;
                            
                                    case 'X' :
                                    case 'x' : current =   10 ; break ;
                            
                                    case 'L' :
                                    case 'l' : current =   50 ; break ;
                            
                                    case 'C' :
                                    case 'c' : current =  100 ; break ;
                            
                                    case 'D' :
                                    case 'd' : current =  500 ; break ;
                            
                                    case 'M' :
                                    case 'm' : current = 1000 ; break ;
                            
                                    default  : current =    0 ; break ;
                                }
                            
                                if ( current < high )
                                    result -= current ;
                                else
                                {
                                   result += current ;
                                   high = current ;
                                }
                            }
                            
                            return ( result ) ;
                            

                            }

                            1 Reply Last reply
                            0
                            • R Ravi Bhavnani

                              Spoiler[^] /ravi

                              My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #29

                              That's dreadful. :wtf:

                              1 Reply Last reply
                              0
                              • C Chris Losinger

                                for well-formed roman numerals, modern rules:

                                int r2d2(const char *r)
                                {
                                int val[128];
                                memset(val,0,sizeof(int)*128);
                                val['I']=1; val['V']=5;
                                val['X']=10; val['L']=50;
                                val['C']=100; val['D']=500; val['M']=1000;

                                int a = 0;
                                for (int cv, pv = 0, i=strlen(r)-1;i>=0;i--)
                                {
                                cv = val[r[i]];
                                a += cv * (pv > cv ? -1 : 1);
                                pv = cv;
                                }

                                return a;
                                

                                }

                                image processing toolkits | batch image processing

                                P Offline
                                P Offline
                                PIEBALDconsult
                                wrote on last edited by
                                #30

                                Seems a waste of RAM.

                                1 Reply Last reply
                                0
                                • C Chris Meech

                                  I once met a well formed roman, when I was touring through Italy. :cool:

                                  Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra] posting about Crystal Reports here is like discussing gay marriage on a catholic church’s website.[Nishant Sivakumar]

                                  A Offline
                                  A Offline
                                  arcosupportus
                                  wrote on last edited by
                                  #31

                                  did you get here number?

                                  1 Reply Last reply
                                  0
                                  • C Chris Maunder

                                    Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                    J Offline
                                    J Offline
                                    jsc42
                                    wrote on last edited by
                                    #32

                                    Apologies if other respondents have used a similar technique, but I have deliberately not looked at the other replies before attempting this challenge so that I am not influenced by other people's ideas. The following is in JavaScript, not obfuscated. The tricks are: Using an object literal as a lookup table and treating the double chars as subtractors from the second single chars (e.g. CM = [CM] + [M] = -100 + 1000 = 900). The only awkward part is preventing the last char being counted twice - once as a single char and once as a double char with no second char (this is done by appending '?').

                                    // Roman to Arabic character translations
                                    function RtoA(r) // r is roman numerals in any case
                                    {
                                    // Roman to Arabic conversion table
                                    var Rch =
                                    {
                                    // Single chars: Add each value separately to the total
                                    I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000,
                                    // Double chars: Modify the sum of the second char as subtractors
                                    CM: -100, CD: -100, XC: -10, XL: -10, IX: -1, IV: -1
                                    };

                                    var	R   = r.toUpperCase();  // Ignore case
                                    var	A   = 0;    // Arabic equivalent
                                    
                                    // Parse the text converting valid single chars and double chars
                                    // Set any invalid single or double char combinations as translating to zero
                                    for (var i = 0; i < R.length; i++)
                                    {
                                    	var	ch	= R.charAt(i);
                                    	A	+= 
                                    		Rch\[ch + (R.charAt(i + 1) || '?')\]	// Double char conversion
                                    		||	Rch\[ch\]	// Single char conversion
                                    		||	0;	// No conversion - invalid char
                                    };	// for
                                    
                                    return	A;
                                    

                                    }

                                    alert(RtoA('MDC')); // 1600
                                    alert(RtoA('mcmxcix')); // 1999

                                    1 Reply Last reply
                                    0
                                    • C Chris Maunder

                                      Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                                      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                      R Offline
                                      R Offline
                                      RobertHarris
                                      wrote on last edited by
                                      #33

                                      First time post so hope this looks OK; 1 CRT "NUMERALS: ": ; INPUT NUM 2 CRT "NUMBER : ":ICONV(NUM, 'NR') 3 END Written in UniVerse BASIC.

                                      1 Reply Last reply
                                      0
                                      • L Lost User

                                        Or, somewhat more tersely,

                                        def r2d3(r,(s,M,C,X,I,z,V,L,D)=["%%s%d"%v for v in[1001,1000,100,10,1,0,5,50,500]]):
                                        return eval("".join([
                                        p%"+-"[eval( p%"%s>"%d%"")]
                                        for d,p in zip(map(eval,'%sz'%r),map(eval,'s%s'%r))
                                        ][1:]))

                                        Y Offline
                                        Y Offline
                                        yiangos
                                        wrote on last edited by
                                        #34

                                        Or, somewhere in between:

                                        def a6(roman):
                                        if len(roman)==0:
                                        return 0
                                        mapping={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
                                        values=[mapping[digit] for digit in roman.upper()]
                                        for i in range(len(values)):
                                        if i

                                        also, added capitalization tolerance, so that "MCM" and "mcm" evaluate the same. I haven't added a check that the argument is a valid roman numeral, but that is left as an exercise to the reader ;P

                                        Φευ! Εδόμεθα υπό ρηννοσχήμων λύκων!
                                        (Alas! We're devoured by lamb-guised wolves!)

                                        1 Reply Last reply
                                        0
                                        • C Chris Maunder

                                          Write a function to convert Roman numerals to Arabic numbers. The smaller the better. Bonus points, as always, for obscure languages and obfuscated assembler.

                                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                          P Offline
                                          P Offline
                                          Pascal Ganaye
                                          wrote on last edited by
                                          #35

                                          I hope it will be obscure enough. ;)

                                          class Program
                                          class Program
                                          {
                                          static int RomanToArabic(string r)
                                          {
                                          int x, y, z = x = y = 0;
                                          foreach (char c in r)
                                          y += ((z = (int)Math.Pow(10, (z = "ivxlcdm".IndexOf((char)(c | ' '))) / 2) * (1 + 4 * (z & 1))) > x ? -2 * x + (x = z) : x = z);
                                          return y;
                                          }

                                              static void Main(string\[\] args)
                                              {
                                                  Console.WriteLine(RomanToArabic("MDC"));	// 1600
                                                  Console.WriteLine(RomanToArabic("mcmxcix"));	// 1999
                                                  Console.ReadKey();
                                              }
                                              
                                          }
                                          

                                          }

                                          L 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups