0

I want to get random alphabet without create list of all alphabets and get random index

I tried this

fun getChar(){
    val alphabets = ('a'..'z').toList()
    return alphabets[Random().nextInt(alphabets.size)]
}
Omar Khaled
  • 439
  • 1
  • 4
  • 16
  • Does this answer your question? [How can I get a random number in Kotlin?](https://stackoverflow.com/questions/45685026/how-can-i-get-a-random-number-in-kotlin) – Madhu Bhat Sep 17 '21 at 14:40
  • 2
    You can just use `('a'..'z').random()` – Madhu Bhat Sep 17 '21 at 14:40
  • I think you mean a random _letter_. An [_alphabet_](https://en.wikipedia.org/wiki/Alphabet) is the _set_ of letters in a language (such as 'a'...'z'). – gidds Sep 20 '21 at 07:55

1 Answers1

2

You can use ASCII Character codes. generate a random number from 97 representing a, to 122 representing z, then use toChar(charCode) to get the corresponding letter.

also see: ASCII Table

ALSO as Madhu Bhat said in the comments you can use ('a'..'z').random() for a more precise way.

Erfan Yeganegi
  • 311
  • 1
  • 9