ภาพรวม
Kotlin มีหลายวิธีสร้างตัวเลขสุ่ม (Random Numbers) ตั้งแต่ API มาตรฐานไปจนถึง Multiplatform Random
วิธีที่ 1: kotlin.random.Random (Multiplatform - แนะนำ)
import kotlin.random.Random
fun main() {
// Int ระหว่าง 0-29 (inclusive start, exclusive end)
val r1 = Random.nextInt(0, 30)
// Int ระหว่าง 1-100
val r2 = Random.nextInt(1, 101)
// Long, Double, Boolean
val rLong = Random.nextLong()
val rDouble = Random.nextDouble() // 0.0 - 1.0
val rBool = Random.nextBoolean()
// List ของค่าสุ่ม
val randomList = List(5) { Random.nextInt(1, 101) }
println(randomList) // เช่น [42, 17, 89, 3, 56]
}
วิธีที่ 2: Range.random() - สำหรับ Range
fun main() {
// Int Range
val num = (1..100).random() // 1 ถึง 100
// Char Range
val char = ('a'..'z').random()
// Closed Range เท่านั้น (open-ended ไม่ได้)
// (1..10).random() ✅
// (1 until 10).random() ❌ Error
}
วิธีที่ 3: List.shuffled() - สลับลำดับ
fun main() {
val numbers = (1..52).toList() // ไพ่ 52 ใบ
val shuffled = numbers.shuffled()
val firstCard = shuffled.first() // ใบแรกหลังสลับ
// หรือ one-liner
val randomCard = (1..52).shuffled().first()
}
วิธีที่ 4: java.util.Random (Legacy JVM Only)
import java.util.Random
fun main() {
val random = Random()
val nextInt = random.nextInt(100) // 0-99
val nextDouble = random.nextDouble()
val nextGaussian = random.nextGaussian() // Normal Distribution
}
วิธีที่ 5: ThreadLocalRandom (High Performance JVM)
import java.util.concurrent.ThreadLocalRandom
fun main() {
val r = ThreadLocalRandom.current()
val int = r.nextInt(1, 101)
val long = r.nextLong(1000, 2000)
}
SecureRandom - สำหรับ Cryptography
import java.security.SecureRandom
fun main() {
val secure = SecureRandom()
val token = secure.nextLong() // Token สำหรับ Security
// หรือ generate bytes
val bytes = ByteArray(32)
secure.nextBytes(bytes)
}
ตารางเปรียบเทียบ
| API | Platform | Use Case | Thread Safe |
|---|---|---|---|
| kotlin.random.Random | Multiplatform | General Purpose ✅ | Yes |
| Range.random() | Multiplatform | Simple Range Random | Yes |
| List.shuffled() | Multiplatform | Shuffle Collection | Yes |
| java.util.Random | JVM Only | Legacy/Compatibility | Yes (but shared) |
| ThreadLocalRandom | JVM Only | High Performance/Concurrent | Yes (Thread-local) |
| SecureRandom | JVM Only | Cryptography/Security | Yes |
แนวทางเลือกใช้
- ทั่วไป:
Random.nextInt(from, until)หรือ(from..until).random() - Multiplatform (Kotlin/JS/Native): ใช้
kotlin.random.Randomเท่านั้น - High Concurrency (JVM):
ThreadLocalRandom - Security/Token/Password:
SecureRandom - Shuffle Deck/List:
list.shuffled()