Skip to content

Instantly share code, notes, and snippets.

@atomsfat
Created December 20, 2013 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomsfat/8059040 to your computer and use it in GitHub Desktop.
Save atomsfat/8059040 to your computer and use it in GitHub Desktop.
cardinal to roman
def cardinalToRoman( int num){
def TreeMap map = [1:"I", 5: "V", 10 : "X", 100 :"C"]
def getLatestKey = {int nu ->
def val = null
for (Map.Entry entry : map.descendingMap().entrySet()) {
def residuo = nu % entry.key;
def division = (nu / entry.key).toInteger();
def nextEntry = division + 1
// println "division ${division}"
if(division > 0){
println "dont go forward ${entry.key}"
val = entry.key
break
}
}
val
}
println "--${num}"
def latest = getLatestKey(num)
def unidad = Math.pow(10,(num / 10).toInteger()).toInteger()
println "unidad $unidad"
def dividendo = num/latest
def residuo = num % latest
println "residuo ${residuo}"
println "latest ${latest}"
println "dividendo ${dividendo}"
nextInMapLatest = getLatestKey(( num + unidad).toInteger())
println "----next${nextInMapLatest}"
def val = map.find{it-> it.key == latest}.value
def unidadVal = map.find{it-> it.key == unidad}.value
println "unidadVal ${unidadVal}"
def nextInMapLatestVal = map.find{it-> it.key == nextInMapLatest}.value
def out = ""
if((num + unidad)/nextInMapLatest ==1){
out = unidadVal + nextInMapLatestVal
}else if(dividendo && residuo == 0){
dividendo.times{ out = out + val }
return out;
}else{
dividendo.times{ out = out + val }
return out + cardinalToRoman(residuo)
}
}
//assert cardinalToRoman(1) == "I";
//assert cardinalToRoman(2) == "II";
assert cardinalToRoman(3) == "III";
//assert cardinalToRoman(4) == "IV";
//assert cardinalToRoman(5) == "V";
assert cardinalToRoman(9) == "IX";
//assert cardinalToRoman(20) == "XX";
assert cardinalToRoman(30) == "XXI";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment