Posted By

TopcatSoftware on 01/09/11


Tagged

conversion


Versions (?)

arabic2roman()


 / Published in: Awk
 

URL: http://www.topcat.hypermart.net/index.html

Simple arabic to roman numeral conversion in awk

  1. function arabic2roman(x, y) {
  2. # arabic to roman numeral conversion in awk
  3. # Topcat Software LLC. - 2010
  4. # http://www.topcat.hypermart.net/index.html
  5. # example: foo = arabic2roman(100)
  6.  
  7. if (!x) {return "nulla"}
  8. if (x > 3999) {return "max input: 3999"}
  9.  
  10. while (x >= 1000) {x -= 1000; y = y "M" }
  11. while (x >= 900) {x -= 900; y = y "CM"}
  12. while (x >= 500) {x -= 500; y = y "D" }
  13. while (x >= 400) {x -= 400; y = y "CD"}
  14. while (x >= 100) {x -= 100; y = y "C" }
  15. while (x >= 90) {x -= 90; y = y "XC"}
  16. while (x >= 50) {x -= 50; y = y "L" }
  17. while (x >= 40) {x -= 40; y = y "XL"}
  18. while (x >= 10) {x -= 10; y = y "X" }
  19. while (x >= 9) {x -= 9; y = y "IX"}
  20. while (x >= 5) {x -= 5; y = y "V" }
  21. while (x >= 4) {x -= 4; y = y "IV"}
  22. while (x >= 1) {x -= 1; y = y "I" }
  23.  
  24. return y
  25.  
  26. }
  27.  
  28. # a 2nd example (more succinct)
  29.  
  30. # awk script converts arabic numerals to roman numerals
  31. # usage example: 'awk -f arabic2roman.awk 100'
  32.  
  33. BEGIN {
  34.  
  35. split("1000 900 500 400 100 90 50 40 10 9 5 4 1", ar)
  36. split("M CM D CD C XC L XL X IX V IV I", ro)
  37.  
  38. print arabic2roman(ARGV[1])
  39.  
  40. }
  41.  
  42. function arabic2roman(x, y, z) {
  43.  
  44. if (!x) {return "nulla"}
  45. if (x > 3999) {return "max input: 3999"}
  46.  
  47. for (y=1; ar[y]; y++) {while (x >= ar[y]) {x -= ar[y]; z = z ro[y]}}
  48.  
  49. return z
  50.  
  51. }

Report this snippet  

You need to login to post a comment.