Groovy web console

subscribe to the feed Subscribe
to this
site

Roman to Numeral Dojo

Published 1 decade ago by Cyril Picat with tags groovy minute inject fold
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
class RomanNumberCategory {

  static def toDecimal(self) {
    switch( self ) {
      case 'I': return 1
      case 'V': return 5
      case 'X': return 10
      case 'L': return 50
      case 'C': return 100
      case 'D': return 500
      case 'M': return 1000
    }
  }
}

def sign = { last, current ->  (current >= last) ? 1 : -1 }

def romanToNumeral = { string ->

  use(RomanNumberCategory) {
    def reverseString = string.reverse()*.toDecimal()
    def last = 0
    reverseString.inject(0) { sum, current -> sum += sign(last, current) * current; last = current; sum }
  }
}

def myvar

assert (myvar = RomanNumberCategory.toDecimal("I")) == 1
assert (myvar = RomanNumberCategory.toDecimal("V")) == 5
assert (myvar = RomanNumberCategory.toDecimal("X")) == 10
assert (myvar = RomanNumberCategory.toDecimal("L")) == 50
assert (myvar = RomanNumberCategory.toDecimal("C")) == 100
assert (myvar = RomanNumberCategory.toDecimal("D")) == 500
assert (myvar = RomanNumberCategory.toDecimal("M")) == 1000

assert (myvar = sign(1,10)) == 1
assert (myvar = sign(10,1)) == -1

assert (myvar = romanToNumeral("I")) == 1
assert (myvar = romanToNumeral("II")) == 2
assert (myvar = romanToNumeral("XVI")) == 16
assert (myvar = romanToNumeral("MDCLXVI")) == 1666
assert (myvar = romanToNumeral("XIV")) == 14
assert (myvar = romanToNumeral("MMMMDCCCLXXXVIII")) == 4888

println "All tests passed!"