Kotlin - Completed RomanNumeral, LinkedList in progress

This commit is contained in:
Anthony C 2017-08-02 10:30:22 -04:00
parent 093878f065
commit 4081083f82
2 changed files with 103 additions and 0 deletions

View file

@ -0,0 +1,61 @@
class Deque<T> {
var firstNode: Node<T>? = null
var lastNode: Node<T>? = null
// Remove value at back
fun pop(): T{
val returnData = lastNode!!.data
lastNode = lastNode?.beforeNode
return returnData
}
// Add value at back
fun push(elem: T): Unit {
if (firstNode == null) {
firstNode = Node<T>(data = elem, beforeNode = null, afterNode = null)
} else {
if (lastNode == null){
this.lastNode = Node<T>(data = elem, beforeNode = firstNode, afterNode = null)
firstNode?.linkBefore(this.lastNode!!)
}
else {
this.lastNode?.linkBefore(Node<T>(data = elem, beforeNode = this.lastNode, afterNode = null))
}
}
}
// Remove value at front
fun shift(): T{
val returnData = firstNode!!.data
firstNode = firstNode?.afterNode
return returnData
}
// Add value at front
fun unshift(elem: T): Unit {
if (firstNode == null) {
firstNode = Node<T>(data = elem, beforeNode = null, afterNode = null)
} else {
if (lastNode == null){
this.lastNode = this.firstNode
firstNode = Node<T>(data = elem, beforeNode = null, afterNode = this.lastNode)
this.lastNode?.linkAfter(firstNode!!)
}
else {
this.firstNode?.linkAfter(Node<T>(data = elem, beforeNode = null, afterNode = this.firstNode))
}
}
}
}
data class Node<R>(val data: R, var beforeNode: Node<R>?, var afterNode: Node<R>?) {
fun linkBefore(afterNode: Node<R>): Unit {
this.afterNode = afterNode
afterNode.beforeNode = this
}
fun linkAfter(beforeNode: Node<R>): Unit {
this.beforeNode = beforeNode
beforeNode.afterNode = this
}
}

View file

@ -0,0 +1,42 @@
class RomanNumeral {
// Implementation lifted from github.com/froderik/roman_numeral_katas
companion object {
fun value(inp: Int): String {
val stringBuilder = StringBuilder()
val thousands = inp / 1000
stringBuilder.append(times(thousands, "M"))
val hundreds = inp / 100 % 10
stringBuilder.append(times(hundreds, "C", "D", "M"))
val tens = inp / 10 % 10
stringBuilder.append(times(tens, "X", "L", "C"))
val ones = inp% 10
stringBuilder.append(times(ones, "I", "V", "X"))
return String(stringBuilder)
}
private fun times(number: Int, char: String): String {
val stringBuilder = StringBuilder()
for (i in 0.. number - 1) {
stringBuilder.append(char)
}
return String(stringBuilder)
}
private fun times(number: Int, onesChar: String, fivesChar: String, tensChar: String): String {
when (number) {
0 -> return ""
1, 2, 3 -> return times(number, onesChar)
4 -> return onesChar + fivesChar
5, 6, 7, 8 -> return fivesChar + times(number - 5, onesChar)
9 -> return onesChar + tensChar
else -> throw IllegalArgumentException("Only single digits allowed - not " + number)
}
}
}
}