Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random dice rolls aren't random

Tags:

random

scala

Simple novice problem, which I strangely haven't been able to conjure a solution for.

I'm making a simple dice roll simulator so I can compare nontransitive dice, as well as normal ones, however the issue is that if I make two dice with the same number of faces and values on said faces, both dice will roll the same value every time. (that is, each roll produces a different number, but both dice have the same value)

Here's my code:

class Die(values: Int*) {
  private val rand: util.Random = new util.Random(compat.Platform.currentTime)
  private val high = values.size + 1
  private val low  = values(0)
  def roll(): Int  = rand.nextInt(high - low) + low
  def this(vals: Range) = this(vals: _*)

  def rollAndCompareTo(that: Die): Symbol = {
    val a = this.roll()
    val b = that.roll()
    if(a > b) 'GT
    else if (a < b) 'LT
    else 'EQ
  }
}

object Program extends App {
  val d61 = new Die(1 to 6)
  val d62 = new Die(1 to 6)

  for(_ <- 1 to 100)
    println(d61 rollAndCompareTo d62)
}

100% of the time, the program will print nothing but 'EQ, because the two dice, despite being different instances created at different times always roll the same value.

I've also tried to add a delay, so that the seed difference is greater, but that doesn't help either.

What would I do to mend this?

like image 365
Electric Coffee Avatar asked Feb 05 '26 10:02

Electric Coffee


1 Answers

Try leaving out the seed for your instance of Random, or use

new util.Random(System.currentTimeMillis)

The specificity of your seed is important if you're making many calls in a short amount of time.

like image 108
dan.john.daly Avatar answered Feb 06 '26 23:02

dan.john.daly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!