Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 11, 2024 21:14
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 dacr/29309fcce3b4bbc65d96f5d4b7921444 to your computer and use it in GitHub Desktop.
Save dacr/29309fcce3b4bbc65d96f5d4b7921444 to your computer and use it in GitHub Desktop.
simple load balancing algorithm / published by https://github.com/dacr/code-examples-manager #812a93f3-e957-4dfc-b9f5-ea8825503faa/bb610ad2b2af27c05bdb1b259a319d58ed3f0e94
// summary : simple load balancing algorithm
// keywords : scala, load-balancing, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 812a93f3-e957-4dfc-b9f5-ea8825503faa
// created-on : 2024-02-06T23:51:44+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.1"
// ---------------------
/* MORE INFORMATION :
- https://twitter.com/crodav/status/1755014365286215948
- https://twitter.com/GrantSlatton/status/1754912113246798036
- https://www.eecs.harvard.edu/~michaelm/postscripts/handbook2001.pdf
*/
import scala.io.AnsiColor.*
import scala.util.Random.*
import scala.math.*
val colors = IndexedSeq(GREEN_B, BLUE_B, CYAN_B, YELLOW_B, MAGENTA_B, RED_B)
def justRandomStrategy(chosenCounters: IndexedSeq[Int]) = {
val index = nextInt(chosenCounters.size)
chosenCounters.updated(index, chosenCounters(index) + 1)
}
def minRandomStrategy(chosenCounters: IndexedSeq[Int]) = {
val index1 = nextInt(chosenCounters.size)
val index2 = nextInt(chosenCounters.size)
val index = if (chosenCounters(index1) < chosenCounters(index2)) index1 else index2
chosenCounters.updated(index, chosenCounters(index) + 1)
}
def toColoredString(chosenCounters: IndexedSeq[Int]): String = {
val min = chosenCounters.min
def color(value: Int) = colors.lift(value - min).getOrElse(colors.last)
chosenCounters.map(v => f"$BLACK${color(v)} $v%2d$RESET").mkString
}
def display(leftChosenCounters: IndexedSeq[Int], rightChosenCounters: IndexedSeq[Int]) = {
println(toColoredString(leftChosenCounters) + " ❚ " + toColoredString(rightChosenCounters))
}
def simulate(howMany: Int, generations: Int): Unit = {
val initialLeft = IndexedSeq.fill(howMany)(0)
val initialRight = IndexedSeq.fill(howMany)(0)
1.to(generations).foldLeft((initialLeft, initialRight)) { case ((left, right), gen) =>
display(left, right)
(justRandomStrategy(left), minRandomStrategy(right))
}
}
simulate(20, 800)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment