Skip to content

Instantly share code, notes, and snippets.

@hixguru
Last active June 12, 2017 06:13
Show Gist options
  • Save hixguru/49c91e032c5b682253ea5d91e7d0dd57 to your computer and use it in GitHub Desktop.
Save hixguru/49c91e032c5b682253ea5d91e7d0dd57 to your computer and use it in GitHub Desktop.
import java.util.*
/**
* Created by hwanik on 2017. 6. 9..
*/
fun main(args: Array<String>) {
val max = 5
try {
println("랜덤숫자: ${getRandom(max)}")
} catch (e: IllegalArgumentException) {
println("제한된 범위의 숫자입니다. max값은 양수여야 합니다.")
}
}
fun getZeroOrOne(): Int {
return Random().nextInt(2)
}
fun getRandom(max: Int): Int {
if (max < 0) {
throw IllegalArgumentException()
} else if (max <= 1) {
return 0
}
val IN_FRONT = 0
val BINARY_NUMBER = 2
val maxToBinary = Integer.toBinaryString(max)
val randomNumber = StringBuilder()
var i = 0
var randomNumberToInt = 0
while (i < maxToBinary.length) {
randomNumber.insert(IN_FRONT, getZeroOrOne())
i++
randomNumberToInt = Integer.parseInt(randomNumber.toString(), BINARY_NUMBER)
if (randomNumberToInt >= max) {
randomNumber.setLength(0)
i = 0
}
}
return randomNumberToInt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment