[英]Creating random string to represent RGB color
Suppose I need to generate random string to represent an RGB color. 假设我需要生成随机字符串来表示RGB颜色。 The string consists of #
and 6 hex digits: eg #ff0000
or #cafe00
. 该字符串包含#
和6个十六进制数字:例如#ff0000
或#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 ? 您将如何改善它?
没有第3方库。
"#%06x".format(scala.util.Random.nextInt(1<<24))
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: 由于存在0到255的三个范围,每个范围都以最大值0xff
表示,并且它们全部串联在一个值中,因此我们可以直接采用0... 0xffffff
范围内的随机值并生成结果字符串:
implicit val arbitraryString: Arbitrary[String] = Arbitrary {
"#" + Gen.choose(0, 0xffffff).toHexString
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.