Thursday, July 4, 2019

Kotlin in Action: Answers to Chapter 3 Exercises

In this post I gave a couple of Java to Kotlin conversion exercises. Here's the answers, or at least one version of the answers:

Exercise 1: Roman Numerals

import java.util.*

// This can only be used to test your results.
private val testList = listOf(
    "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
    "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX",
    "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII",
    "XXVIII", "XXIX", "XXX", "XXXI", "XXXII", "XXXIII", "XXXIV",
    "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL", "XLI",
    "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII",
    "XLIX", "L", "LI", "LII", "LIII", "LIV", "LV", "LVI", "LVII",
    "LVIII", "LIX", "LX", "LXI", "LXII", "LXIII", "LXIV", "LXV",
    "LXVI", "LXVII", "LXVIII", "LXIX", "LXX", "LXXI", "LXXII",
    "LXXIII", "LXXIV", "LXXV", "LXXVI", "LXXVII", "LXXVIII",
    "LXXIX", "LXXX", "LXXXI", "LXXXII", "LXXXIII", "LXXXIV",
    "LXXXV", "LXXXVI", "LXXXVII", "LXXXVIII", "LXXXIX", "XC", "XCI",
    "XCII", "XCIII", "XCIV", "XCV", "XCVI", "XCVII", "XCVIII",
    "XCIX", "C")

private val romanNumeralMap = TreeMap(mapOf(
    1 to "I",
    4 to "IV",
    5 to "V",
    9 to "IX",
    10 to "X",
    40 to "XL",
    50 to "L",
    90 to "XC",
    100 to "C"))

fun main() {
    var passed = true
    for (i in 1..100) {
        val romanNumeral = i.toRomanNumeral()
        println(romanNumeral)
        passed = passed && romanNumeral == testList[i-1]
    }
    println(if (passed) "Passed" else "Failed")
}

fun Int.toRomanNumeral() : String {
    val floorKey = romanNumeralMap.floorKey(this)
    if (this == floorKey) {
        return romanNumeralMap[this]?:""
    }
    return (romanNumeralMap[floorKey]?:"") +
            (this - floorKey).toRomanNumeral()
}

Exercise 2: SQL Query String

private const val TABLE_NAME = "blog_posts"

fun main() {
    val query = """SELECT id, data
                  .FROM $TABLE_NAME
                  .WHERE data->>'userId' = ?""".trimMargin(".")
    println(query)
}