Last active
May 25, 2024 08:39
-
-
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/e004021d72768408b3980631f702a4ae2dcea321
This file contains hidden or 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
// 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.4.2" | |
// --------------------- | |
/* 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