Last active
February 9, 2017 04:13
-
-
Save sinanduman/cf63ad2328770756ac6fb280e5d49864 to your computer and use it in GitHub Desktop.
Lexical ordering Roman Numbers in King Titles
This file contains 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
package algo | |
class Roman(kings: Array[String]) { | |
val basicLetters = Map( | |
'I' -> 1, | |
'V' -> 5, | |
'X' -> 10, | |
'L' -> 50, | |
'C' -> 100, | |
'D' -> 500, | |
'M' -> 1000) | |
def sortLetters(): Array[String] = { | |
kings. | |
map { x => x.split(" ") }. | |
sortWith { (x, y) => sortByLexical(x(1), y(1)) }. | |
map { z => z.mkString(" ") } | |
} | |
def sortByLexical(s1: String, s2: String) = { | |
computeNumericVal(s1) < computeNumericVal(s2) | |
} | |
def sortTest(str: Array[String]): Unit = { | |
println("[Kings in Order]") | |
for (s: String <- str) { | |
print("=> ") | |
println(s) | |
} | |
} | |
def computeNumericVal(roman: String): Int = { | |
var acc = 0 | |
var previousSymbol: Char = roman(0) | |
for (currentSymbol: Char <- roman) { | |
if (basicLetters(currentSymbol) > basicLetters(previousSymbol)) { | |
acc = (basicLetters(currentSymbol) - (basicLetters(previousSymbol) * 2)) + acc | |
} else { | |
acc += basicLetters(currentSymbol) | |
} | |
previousSymbol = currentSymbol | |
} | |
acc | |
} | |
} |
This file contains 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
package algo | |
object RomanDemo { | |
def main(args: Array[String]) { | |
val letters = Array("Luis X", "Luis III", "Luis L", "Luis VII", "Luis XIX") | |
val roman = new Roman(letters) | |
val sortedLetters = roman.sortLetters() | |
roman.sortTest(sortedLetters) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made revisions at Roman class to compute numeric values on the fly.