Last active
May 25, 2023 08:25
-
-
Save channingwalton/923965d04d2697037f6b6307dc80cada to your computer and use it in GitHub Desktop.
Randomly distribute N items across M buckets
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
package example | |
import scala.util.Random | |
object Hello extends App { | |
val items = (0 to 10).toList.map(i => s"Item $i") | |
val numberOfBuckets = 10 | |
val working: Map[String, Double] = items.map(i => (i, Random.nextDouble())).toMap | |
val bucketSize = 1.0 / numberOfBuckets | |
val buckets: Map[Int, Iterable[String]] = working.groupMap { case (item, rnd) => (rnd / bucketSize).toInt }(_._1) | |
val sorted: List[(Int, Iterable[String])] = buckets.toList.sortBy(_._1).toList | |
println( | |
sorted | |
.map { case (bucket, items) => | |
s"Bucket $bucket: ${items.mkString(",")}" | |
} | |
.mkString("\n") | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: