Wednesday, July 6, 2022

Day 21/100 Roman Numeral

Day 21/100 Roman Numeral

MMXX has been a bad year!


I'll just do a quick run today. Basically, I'm intrigued by the possibility of parsing text with text fragments, instead per character or per words. So, I decided to put out an array of text and the converted value. Since this is a quick experiment, and I want to have an actual program, I decided to do Roman numeral conversion. Leet Code 13


I don't have to do Roman numeral conversion program. I can do Morse Code, or Phonetic Alphabet, etc. But Roman numeral conversion is simple enough, so why not?


int roman(char *num) {
  int i; int n=0; int l;
  for (i=0;i<strlen(num);i++) num[i]=toupper(num[i]);
  while (strlen(num)) {
    for (i=0;i<MAXENTRY;i++) {
      l=strlen(Romc[i]);
      if (!strncmp(Romc[i],num,l)) {
        n+=Romv[i]; num+=l; break;
      }
    }
  }
  return n;
}


It took me about an hour to do this, simply because I forgot to Initialize the table! Oh, dear. Can we say C is a terrible language to work with? Not really. I mean, what kind of computer programmer is it, to forget to initialize the table? Also, what kind of computer language can help with that? Syntax error is easy. Semantic error, however, is something you just have to own it.


#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAXDIGIT 5
#define MAXENTRY 13

char Romc[MAXENTRY][MAXDIGIT];
int  Roml[MAXENTRY];
int  Romv[MAXENTRY];

int roman(char *num) {
  int i; int n=0; int l;
  for (i=0;i<strlen(num);i++) num[i]=toupper(num[i]);
  while (strlen(num)) {
    for (i=0;i<MAXENTRY;i++) {
      l=strlen(Romc[i]);
      if (!strncmp(Romc[i],num,l)) {
        n+=Romv[i]; num+=l; break;
      }
    }
  }
  return n;
}

void Init() {
  strcpy(Romc[0],"CM"); Romv[0]=900;
  strcpy(Romc[1],"CD"); Romv[1]=400;
  strcpy(Romc[2],"XC"); Romv[2]=90;
  strcpy(Romc[3],"XL"); Romv[3]=40;
  strcpy(Romc[4],"IX"); Romv[4]=9;
  strcpy(Romc[5],"IV"); Romv[5]=4;
  strcpy(Romc[6],"M");  Romv[6]=1000;
  strcpy(Romc[7],"D");  Romv[7]=500;
  strcpy(Romc[8],"C");  Romv[8]=100;
  strcpy(Romc[9],"L");  Romv[9]=50;
  strcpy(Romc[10],"X"); Romv[10]=10;
  strcpy(Romc[11],"V"); Romv[11]=5;
  strcpy(Romc[12],"I"); Romv[12]=1;
}

int main (int argc, char *argv[] ) {
  int i;

  if   (argc<2) {
    puts("Usage: roman ROMAN\n");
    return 0;
  }
  Init();
  for (i=1;i<argc;i++) {
    printf("%6d %s\n",roman(argv[i]),argv[i]);
  }
  return 0;
}


One more thing: You probably notice that the logic used here isn't the same as the logic used everywhere else. That's because the goal isn't to convert Roman numerals per se, but as an exercise to parse partial text not separated by words. Those of you who depends on pre-existing libraries, do you even have one? In any language? Sometimes, you just have to buckle down and make your own library. There's no way around it if you want to work on the bleeding edge.


No comments:

Post a Comment