]> gitweb.factorcode.org Git - factor.git/commitdiff
math.extras: adding weighted-randoms
authorJohn Benediktsson <mrjbq7@gmail.com>
Sat, 18 Feb 2023 00:56:08 +0000 (16:56 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sat, 18 Feb 2023 00:56:08 +0000 (16:56 -0800)
extra/math/extras/extras.factor

index 50de00759507f6f3f7a16e11af2eedd988d27ea9..8dcf26b6d68ce6135fe78614437b39c4be110c80 100644 (file)
@@ -5,8 +5,9 @@ USING: accessors arrays assocs byte-arrays combinators
 combinators.short-circuit compression.zlib grouping kernel math
 math.bitwise math.combinatorics math.constants math.functions
 math.order math.primes math.primes.factors math.statistics
-math.vectors random ranges ranges.private sequences
-sequences.extras sets sorting sorting.extras ;
+math.vectors namespaces random random.private ranges
+ranges.private sequences sequences.extras sets sorting
+sorting.extras ;
 
 IN: math.extras
 
@@ -201,6 +202,10 @@ PRIVATE>
 : weighted-random ( histogram -- obj )
     unzip cum-sum [ last >float random ] [ bisect-left ] bi swap nth ;
 
+: weighted-randoms ( length histogram -- seq )
+    unzip swap [ cum-sum [ last >float random-generator get ] keep ] dip
+    '[ 0.0 _ _ (uniform-random-float) _ bisect-left _ nth ] replicate ;
+
 : unique-indices ( seq -- unique indices )
     [ members ] keep over dup length <iota>
     H{ } zip-as '[ _ at ] map ;