Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

better way to do it?

Status
Not open for further replies.

zanza

Programmer
Feb 18, 2002
89
US
just because i felt like trying, i wrote this app to translate roman numerals back and forth. no, this isnt homework. :p just practice.

anyway, the way i went about doing it is just (for from arabic to roman) getting the length of the string and using that as a basis to convert one decimal place at a time. simple enough.

but from roman to arabic was obviously a tad more difficult. in the end, i decided to transverse the inputed string backwards, using the add and subtract rules of roman numerals to determine the value needed and just add that value each time.

my curiousity is this: im doing it simply with a large amount of cases and ifs. this is the source file: is there some much easier way to do it? or even a more efficient way despite added complexity?

thanks.

žÅNžÅ
 
It's certainly a long-winded way that's for sure.

In the past, I've used a table like this and a small function (no more than 20 lines IIRC) to walk the string extracting component values, and summing the results.
Code:
struct {
  int value;
  char *roman;
} pairs[] = {
  { 1000,  "M" },
  {  900, "CM" },
  {  500,  "D" },
  {  400, "CD" },
  {  100,  "C" },
  {   90, "XC" },
  {   50,  "L" },
  {   40, "XL" },
  {   10,  "X" },
  {    9, "IX" },
  {    5,  "V" },
  {    4, "IV" },
  {    1,  "I" },
};
You compare the start of your roman numeral with each prefix in the table, and if its a match you
- remove the prefix from your roman string
- add the associated value to the total

Eg.
MCMLXXXIV
Matches in 7 passes over the string the following components of the roman numeral
[tt]M - add 1000
CM - add 900
L - add 50
X - add 10
X - add 10
X - add 10
IV - add 4[/tt]

--
 
sehr nett! :) thanks.

the problem with programming is that you must be familiar with your material before you do something good with it. i wasnt very good with roman numerals before i started this mini-project. ^^;;

žÅNžÅ
 
Nice approach, Salem. I like it.
And zanza, thanks for posting this one. Non-serious little things like this still get stowed away in odd corners of people's memories and pop out when a similar, but work-related serious requirements arise.
 
*nods*

i think im still learning C, so the majority of the applications i write are just for fun. but even still, when i consider myself good enough at the language to be able to teach it, writing programs just to solve an inconsequential problem is half the fun of having this skil. :)

žÅNžÅ
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top