Skip to content

Instantly share code, notes, and snippets.

@channingwalton
Last active May 25, 2023 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save channingwalton/923965d04d2697037f6b6307dc80cada to your computer and use it in GitHub Desktop.
Save channingwalton/923965d04d2697037f6b6307dc80cada to your computer and use it in GitHub Desktop.
Randomly distribute N items across M buckets
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")
)
}
@channingwalton
Copy link
Author

channingwalton commented May 25, 2023

Example output:

Bucket 0: Item 8
Bucket 2: Item 4,Item 3,Item 9
Bucket 3: Item 7,Item 2,Item 6
Bucket 6: Item 5,Item 0,Item 10
Bucket 7: Item 1
Bucket 1: Item 4
Bucket 2: Item 9
Bucket 3: Item 5,Item 7
Bucket 5: Item 0
Bucket 6: Item 10,Item 6
Bucket 7: Item 8,Item 3
Bucket 8: Item 1,Item 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment