import java.util.*

class Cipher() {
    var key: String

    constructor(key: String) : this() {
        require(key.isNotEmpty())
        require(key.all { it.isLowerCase() })
        this.key = key
    }

    init {
        val rand = Random()
        val stringBuilder = StringBuilder()

        for (i in 0..99) {
            stringBuilder.append('a' + rand.nextInt(26))
        }

        key = String(stringBuilder)

    }

    fun encode(s: String): String {
        require(s.length <= key.length)
        val stringBuilder = StringBuilder()

        for ((index, i) in s.withIndex()){
            var charToAppend: Char = i + (key[index].toInt() - 'a'.toInt())
            if (charToAppend.toInt() > 'z'.toInt()){
                charToAppend = charToAppend - 26
            }
            stringBuilder.append(charToAppend)
        }

        return String(stringBuilder)
    }

    fun decode(s: String): String {
        require(s.length <= key.length)
        val stringBuilder = StringBuilder()

        for ((index, i) in s.withIndex()){
            var charToAppend: Char = i - (key[index].toInt() - 'a'.toInt())
            if (charToAppend.toInt() < 'a'.toInt()){
                charToAppend = charToAppend + 26
            }
            stringBuilder.append(charToAppend)
        }

        return String(stringBuilder)
    }

}