Skip to content

Instantly share code, notes, and snippets.

@Darkyenus
Last active January 23, 2020 22:41
Show Gist options
  • Save Darkyenus/881f35e224887c748460337c5b282c11 to your computer and use it in GitHub Desktop.
Save Darkyenus/881f35e224887c748460337c5b282c11 to your computer and use it in GitHub Desktop.
Implementation of Vose's Alias algorithm for weighted sampling from discrete set of values (picking random item with a bias)
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*/
package com.darkyen.worldSim.util
import kotlin.random.Random
/**
* Sampling of weighted discrete values.
* Implements Vose's Alias algorithm described by Keith Schwarz at [https://www.keithschwarz.com/darts-dice-coins/].
*/
class WeightedSampler<T>(vararg items:Weighted<T>) {
private val items:Array<Any?> = Array(items.size) { items[it].value }
private val probability = FloatArray(items.size) { 1f }
private val alias = IntArray(items.size)
init {
assert(items.isNotEmpty())
val normalizationFactor = items.size / items.fold(0f) { acc, w -> acc + w.weight }
val workingProbabilities = FloatArray(items.size) { items[it].weight * normalizationFactor }
val small = IntArray(items.size)
val large = IntArray(items.size)
var smallI = 0
var largeI = 0
for (i in items.indices) {
if (workingProbabilities[i] < 1f) {
small[smallI++] = i
} else {
large[largeI++] = i
}
}
val probability = probability
val alias = alias
while (smallI > 0 && largeI > 0) {
val l = small[--smallI]
val g = large[--largeI]
probability[l] = workingProbabilities[l]
alias[l] = g
val pg = workingProbabilities[g] + workingProbabilities[l] - 1f
workingProbabilities[g] = pg
if (pg < 1f) {
small[smallI++] = g
} else {
large[largeI++] = g
}
}
}
fun sample(random:Random):T {
val probability = probability
val column = random.nextInt(probability.size)
val index = if (random.nextFloat() < probability[column]) column else alias[column]
@Suppress("UNCHECKED_CAST")
return items[index] as T
}
fun sample(random:java.util.Random):T {
val probability = probability
val column = random.nextInt(probability.size)
val index = if (random.nextFloat() < probability[column]) column else alias[column]
@Suppress("UNCHECKED_CAST")
return items[index] as T
}
fun sample():T {
return sample(Random)
}
}
class Weighted<T>(val value:T, val weight:Float)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment