Created
January 29, 2018 04:44
-
-
Save zerobasedindex/5629c8cc5c5afec6974b682e80aacaff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
fun pickRandomPercentage(counts: Array<Pair<Int, Int>>): Int { | |
val total = counts.sumBy { src -> src.second } | |
println("Total: ${total}") | |
var random = Random().nextInt(total) + 1 // Random inclusive between 1 and total | |
for ((value, count) in counts) { | |
println("Random: ${random} Value: ${value} Count ${count}") | |
if (random <= count) { | |
return value; | |
} | |
random = random - count; | |
} | |
return -1 | |
} | |
fun main(args: Array<String>) { | |
// Create array of pairs, [{1: 5}, {2: 10}, {3: 20}, {4: 2}] | |
val counts = arrayOf((1 to 5), (2 to 10), (3 to 20), (4 to 2)) | |
println("Random Value Pick: ${pickRandomPercentage(counts)}!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment