• + 0 comments

    I've developed this algorithm in Kotlin. I think by using a map reduces the complexity and makes the code more readable and flexible. Regarding the when clause it may not be the most dynamic option but it seems to me the most performant.

    private val map = mapOf(
        1 to "one",
        2 to "two",
        3 to "three",
        4 to "four",
        5 to "five",
        6 to "six",
        7 to "seven",
        8 to "eigth",
        9 to "nine",
        10 to "ten",
        11 to "eleven",
        12 to "twelve",
        13 to "thirteen",
        14 to "fourteen",
        15 to "quarter",
        16 to "sixteen",
        17 to "seventeen",
        18 to "eighteen",
        19 to "nineteen",
        20 to "twenty",
        21 to "twenty one",
        22 to "twenty two",
        23 to "twenty three",
        24 to "twenty four",
        25 to "twenty five",
        26 to "twenty six",
        27 to "twenty seven",
        28 to "twenty eight",
        29 to "twenty nine",
        30 to "half",
    )
    
    fun timeInWords(h: Int, m: Int): String {
        return when {
            m == 0 -> map.get(h) + " o' clock"
            m == 1 -> map.get(1) + " minute past " + map.get(h)
            m == 15 ||
            m == 30 -> map.get(m) + " past " + map.get(h)
            m < 30 -> map.get(m) + " minutes past " + map.get(h)
            m == 45 -> map.get(15) + " to " + map.get(h + 1)
            m == 59 -> map.get(1) + " minutes to " + map.get(h + 1)
            else -> map.get(60 - m) + " minutes to " + map.get(h + 1)
        }
    }