/** * Follow the instructions and iterate over the text forwards and backwards, * keeping track of which positions have been filled. * To decrypt, use the same algorithm, but instead of filling an empty * position, append the letter that is at the index of the ciphertext where * we would be placing a letter. * * Time complexity: O(|k|*|s|) * * @author Finn Lidbetter */ fun main() { val tokens = readln().split(" ") val action = tokens[0] val key = tokens[1] val text = readln().map{ it -> if (it.isLetter()) { it.lowercaseChar() } else { "" } }.joinToString("") val dArr = key.map { it -> it - 'a' + 2 } var decrypted = Array(text.length) { '_' } var resultArr = Array(text.length) { '_' } var dIndex = 0 var direction = 1 var textIndex = 0 while (textIndex < text.length) { var emptyCount = 0 var start = 0 var end = resultArr.size if (direction == -1) { start = resultArr.size - 1 end = -1 } var rIndex = start while (rIndex != end) { if (resultArr[rIndex] == '_') { emptyCount++ } if ((dIndex < dArr.size && emptyCount == dArr[dIndex]) || (dIndex >= dArr.size && emptyCount == 1)) { emptyCount = 0 resultArr[rIndex] = text[textIndex] decrypted[textIndex] = text[rIndex] //println(resultArr.joinToString("")) textIndex++ if (textIndex >= text.length) { break } } rIndex += direction } dIndex++ direction *= -1 } if (action.equals("E")) { println(resultArr.joinToString("")) } else { println(decrypted.joinToString("")) } }