• + 0 comments

    Kotlin proposal

    import java.io.*
    import java.math.*
    import java.security.*
    import java.text.*
    import java.util.*
    import java.util.concurrent.*
    import java.util.function.*
    import java.util.regex.*
    import java.util.stream.*
    import kotlin.collections.*
    import kotlin.comparisons.*
    import kotlin.io.*
    import kotlin.jvm.*
    import kotlin.jvm.functions.*
    import kotlin.jvm.internal.*
    import kotlin.ranges.*
    import kotlin.sequences.*
    import kotlin.text.*
    
    /*
     * Complete the 'encryption' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts STRING s as parameter.
     */
    
    fun encryption(s: String): String {
        val trimmed: String = s.replace(" ", "")
        val lengthTrimmed = trimmed.length
        val sqrt: Double = Math.sqrt(lengthTrimmed.toDouble())
        
        var rows = sqrt.toInt()
        var columns = if(sqrt % rows == 0.0) { // Cuadratico we
            rows
        } else { // Rectangular we
            rows + 1
        }
        
        if(rows * columns < lengthTrimmed){
            rows++
        }
        
        val words = mutableListOf<String>()
        for(r in 0 until rows){
            words.add(getSubstringSegment(trimmed, r, columns))
        }
        
        return transformWordsList(words, columns).joinToString(" ")
    
    }
    
    private fun transformWordsList(words: List<String>, eachWordSize: Int): List<String> {
        
        val result = mutableListOf<String>()
        for(y in 0 until eachWordSize){
            val sb = StringBuilder("")
            for(x in 0 until words.size){
                if(y < words.get(x).length) {
                    sb.append("${words.get(x)[y]}")
                }
            }
            result.add(sb.toString())
        }
        return result
    }
    
    // (7, 8) 0 -> 0,7; 1 -> 8, 15; 2 -> 16, 23
    private fun getSubstringSegment(s: String, row: Int, eachWordSize: Int): String {
        val startIndexInc = row * eachWordSize
        val endIndexExc = startIndexInc + eachWordSize
        return s.substring(startIndexInc, if(endIndexExc > s.length) s.length else endIndexExc)
    }
    
    fun main(args: Array<String>) {
        val s = readLine()!!
    
        val result = encryption(s)
    
        println(result)
    }