Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
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/12953a22121dc26dd391613b3b9a5192 to your computer and use it in GitHub Desktop.
Save dacr/12953a22121dc26dd391613b3b9a5192 to your computer and use it in GitHub Desktop.
Compare homogeneity of some simple custom random generators using doodle (increase XSS !!) / published by https://github.com/dacr/code-examples-manager #7d55268b-312b-4dae-b62b-77eb2c950ebf/fe08b96f3bf6902357e6df8695665035648f9fe3
// summary : Compare homogeneity of some simple custom random generators using doodle (increase XSS !!)
// keywords : scala, random, rng, scalatest, doodle
// 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 : 7d55268b-312b-4dae-b62b-77eb2c950ebf
// created-on : 2019-09-10T21:18:05Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.2.2"
//> using dep "org.creativescala::doodle:0.18.0"
// using java-opt -Xss2g
// ---------------------
class ScalaDefaultRandom(seed:Long = System.currentTimeMillis()) {
final def nextInt(n:Int):Int = (scala.math.random()*n).toInt
}
class BasicFastRandom(seed: Long = System.currentTimeMillis()) {
private var g_seed = (seed >> 16 & 0x7FFFFFFF).toInt
final def nextBoolean = nextInt(2) != 0
final def nextInt(n: Int) = {
g_seed = 214013 * g_seed + 2531011
((g_seed >> 16) & 0x7FFF) % n
}
}
class XORShift32(val seed: Long = System.currentTimeMillis()) {
private var cseed = seed
private def randomInt = {
var x = cseed
x ^= (x << 13)
x ^= (x >>> 17)
x ^= (x << 5)
cseed = x
x
}
final def nextInt(bound: Int):Int = ((randomInt & 0x7fffff) % bound).toInt
}
import doodle.image._
import doodle.image.syntax._
import doodle.java2d._
import cats.instances.list._
import doodle.core._
import doodle.image.syntax.all.TraverseImageOps
import doodle.image.syntax.all.ImageOps
import cats.effect.unsafe.implicits.global
def showRng(nextInt: Int => Int, color: Color) = {
val circle = Image.circle(1).noFill.strokeWidth(1).strokeColor(color)
val count = 20000
1.to(count)
.toList
.map(f => circle.at(nextInt(250), nextInt(250)))
.allOn
}
val seed = 500L
val i1 = showRng(new BasicFastRandom(seed).nextInt, Color.red)
val i2 = showRng(new ScalaDefaultRandom(seed).nextInt, Color.blue)
val i3 = showRng(new XORShift32(seed).nextInt, Color.green)
i1.beside(i2).beside(i3).draw()
scala.io.StdIn.readLine("Enter to exit...") // required when run as a script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment