sbeve
02/11/2021, 9:13 PMconst val LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"
const val UPPER_CASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun rotateLetter(input: Char, rotations: Int): Char {
val isUpperCase = input in UPPER_CASE_LETTERS
val isLowerCase = input in LOWER_CASE_LETTERS
var variableRotations = rotations
var variableInput = input
while (variableRotations != 0) {
when {
isUpperCase -> {
if (variableInput.toInt() == 90) variableInput = 'A'
else variableInput += 1
}
isLowerCase -> {
if (variableInput.toInt() == 122) variableInput = 'a'
else variableInput += 1
}
else -> return input
}
variableRotations--
}
return variableInput
}
Nir
02/11/2021, 9:15 PMNir
02/11/2021, 9:16 PMsbeve
02/11/2021, 9:16 PMMarc Knaup
02/11/2021, 9:22 PMval isUpperCase = input in 'A' .. 'Z'
ephemient
02/11/2021, 9:22 PMval isUpperCase = input in 'A'..'Z'
Kotlin will optimize it to 2 comparisons. your current in
check requires 26 comparisonsLuke
02/11/2021, 9:23 PMinput.toInt() + rotations
and then, depending on if (input.isUppercase())
you can subtract 90 or 122 if neededMarc Knaup
02/11/2021, 9:24 PMwhen
are constant within the loop.
I’d use while
inside when
, not the other way round.
Or is it a bug and you want isUpperCase = …
meant to be in the while
loop?Nir
02/11/2021, 9:26 PMNir
02/11/2021, 9:26 PMephemient
02/11/2021, 9:29 PMNir
02/11/2021, 9:29 PMephemient
02/11/2021, 9:30 PMif (input in 'A'..'Z' || input in 'a'..'z') {
val codePoint = input.toInt()
(codePoint and 0x1F.inv() or (codePoint.and(0x1F) - 1 + rotations) % 26 + 1).toChar()
} else {
input
}
ephemient
02/11/2021, 9:31 PMsbeve
02/11/2021, 10:01 PMsbeve
02/11/2021, 10:01 PMLuke
02/11/2021, 10:25 PMrotations
to your char, and if you busted z/Z, you subtract to return to a valid output, and you return the result.sbeve
02/11/2021, 10:41 PMephemient
02/12/2021, 1:18 AMit and 0x1F.inv()
turns A..Z into 64 and a..z into 96
(it and 0x1F) - 1
turns A..Z, a..z into 0-25
((it and 0x1F) - 1 + rotations) % 26
turns A..Z, a..z into 0-25, rotated
it and 0x1F.inv() or (((it and 0x1F) - 1 + rotations) % 26 + 1)
combines them back to the expected ASCII