5

My problem is very simple. I have the following:

enum Colors:
  case Blue, Red, Green

How can I choose a random element from this enum? I tried the solution from this question but it didn't work.

dan1st
  • 12,568
  • 8
  • 34
  • 67
olimath
  • 71
  • 4

2 Answers2

3

You can use Random.nextInt to generate an index of a random enum value.

This avoids shuffling the Array of values, and generates only one random number.

import scala.util.Random

enum Colors:
  case Blue, Red, Green

object Colors:
  private final val colors = Colors.values

  def random: Colors = colors(Random.nextInt(colors.size))

@main def run: Unit =
  println(Colors.random)
Kolmar
  • 14,086
  • 1
  • 22
  • 25
2
enum Colors:
  case Blue, Red, Green

@main def run: Unit = 
  import scala.util.Random

  val mycolor = Colors.values

  println(Random.shuffle(mycolor).head)

olimath
  • 71
  • 4