Is there a more concise way of doing the following...
# announcements
t
Is there a more concise way of doing the following:
Copy code
fun charToNumber(input: Char): Int {
    val numbersToLetters = listOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z')

    return numbersToLetters.indexOf(input.toUpperCase()) + 1
}
e
Copy code
('A'..'Z').indexOf(input.toUpperCase())
👍 4
r
'A'.toInt() - 64
(for 1 indexed) See http://www.asciitable.com/
😇 1
👍 1
e
yes, Kotlin can optimize out some usages of constant ranges but this isn't one of them, CharRange.indexOf() results in a linear scan like Tom's original code
it'll be a little more complex to map non-letters to -1, but not by much
something simple could be
Copy code
when (input) {
    'A'..'Z' -> input.toInt() - 'A'.toInt()
    'a'..'z' -> input.toInt() - 'a'.toInt()
    else -> -1
}
i
To add to the above snippet ⬆️,
toInt
conversion is not necessary, just
input - 'A'
will do.
e
oh I didn't realize the overloads were such that Char - Char = Int and Char - Int = Char. just checked now, yes that works the right way right out of the box