0

Suppose I need to generate random string to represent an RGB color. The string consists of # and 6 hex digits: e.g. #ff0000 or#cafe00.

I am doing it with random data generator like that:

import com.danielasfregola.randomdatagenerator.RandomDataGenerator._
import org.scalacheck.{Arbitrary, Gen}

def randomRGB(): String = {

  implicit val arbitraryString: Arbitrary[String] = Arbitrary {
    for {
      r <- Gen.choose(0, 255)
      g <- Gen.choose(0, 255)
      b <- Gen.choose(0, 255)
    } yield "#" + r.toHexString + g.toHexString + b.toHexString
  }

  random[String]
}

How would you improve it ?

Michael
  • 41,026
  • 70
  • 193
  • 341

2 Answers2

3

Without 3rd party libs.

"#%06x".format(scala.util.Random.nextInt(1<<24))
Hayk Hakobyan
  • 309
  • 2
  • 8
1

Since there are three ranges of 0 to 255, each represented with max of 0xff and they all are concatenated in a single value, we can directly take a random value in the range of 0... 0xffffff and produce the resulting string:

implicit val arbitraryString: Arbitrary[String] = Arbitrary {
  "#" + Gen.choose(0, 0xffffff).toHexString
}
Antot
  • 3,904
  • 1
  • 21
  • 27