scalarandom-data

Creating random string to represent RGB color


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 ?


Solution

  • 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
    }