Last active
June 7, 2019 06:50
-
-
Save adriantache/58df41dc683b934c132678bafd7d81e4 to your computer and use it in GitHub Desktop.
Roman Numeral Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
val inputString = | |
"I XV XIII XXX MM CLIV CM LXIX DX III XIX XVI CMXLIV M V IV CMLXIX MX CMX VIII DI XXIX XCIX MMMMMMMMMMCM" | |
val numberList = getNumberList(inputString) | |
numberList.sort() | |
for (i in numberList) { | |
printRomanNumeral(i) | |
} | |
} | |
private fun getNumberList(inputString: String): MutableList<Int> { | |
val numberList = mutableListOf<Int>() | |
var acc = 0 | |
var lastValue = 0 | |
for (i in inputString.length - 1 downTo 0) { | |
val symbol = inputString[i] | |
if (symbol == ' ') { | |
numberList.add(acc) | |
acc = 0 | |
lastValue = 0 | |
continue | |
} | |
val number = when (symbol) { | |
'I' -> 1 | |
'V' -> 5 | |
'X' -> 10 | |
'L' -> 50 | |
'C' -> 100 | |
'D' -> 500 | |
'M' -> 1000 | |
else -> 0 | |
} | |
//subtract number if of the format IV, IX, XL, LC, CD, CM | |
acc += when { | |
(number == 1 && (lastValue == 5 || lastValue == 10)) || | |
(number == 10 && (lastValue == 50 || lastValue == 100)) || | |
(number == 100 && (lastValue == 500 || lastValue == 1000)) -> -number | |
else -> number | |
} | |
if (i != 0) lastValue = number | |
else numberList.add(acc) | |
} | |
return numberList | |
} | |
fun printRomanNumeral(i: Int) { | |
var x = i | |
var powTen = 0 | |
var string = "" | |
while (x > 0) { | |
//fix for very large numbers | |
if (powTen == 3) { | |
string = getRoman(x, powTen) + string | |
break | |
} | |
val digit = x.rem(10) | |
if (digit != 0) string = getRoman(digit, powTen) + string | |
x /= 10 | |
powTen++ | |
} | |
print("$string ") | |
} | |
fun getRoman(digit: Int, powTen: Int): String { | |
when (powTen) { | |
0 -> return when (digit) { | |
in 1..3 -> "I".repeat(digit) | |
4 -> "IV" | |
5 -> "V" | |
in 6..8 -> "V" + "I".repeat(digit - 5) | |
9 -> "IX" | |
else -> "" | |
} | |
1 -> return when (digit) { | |
in 1..3 -> "X".repeat(digit) | |
4 -> "XL" | |
5 -> "L" | |
in 6..8 -> "L" + "X".repeat(digit - 5) | |
9 -> "XC" | |
else -> "" | |
} | |
2 -> return when (digit) { | |
in 1..3 -> "C".repeat(digit) | |
4 -> "CD" | |
5 -> "D" | |
in 6..8 -> "D" + "C".repeat(digit - 5) | |
9 -> "CM" | |
else -> "" | |
} | |
else -> return "M".repeat(digit) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment