Reputation: 1280
I want to pick random element from given list:
def randomAlphaNumericChar(): Char = {
val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toCharArray
Gen.oneOf(ALPHA_NUMERIC_STRING)
}
So currently this now compile:
type mismatch; found : org.scalacheck.Gen[Char] required: Char Gen.oneOf(ALPHA_NUMERIC_STRING)
Upvotes: 0
Views: 334
Reputation: 20435
For
val xs = ('a' to 'z') ++ ('A' to 'Z') ++ (1 to 9)
try
xs.maxBy(_ => scala.util.Random.nextInt)
Here maxBy
applies a function to each element of the collection and then selects the maximum value returned by the function applied to each element. In this case the function is a random value returned from Random.nextInt
.
Upvotes: 1
Reputation: 1178
def randomAlphaNumericChar(): Char = {
/*
ASCII Codes
[0-9]: (48 to 57)
[A-Z]: (65 to 90)
[a-z]: (97 to 122)
*/
val alphabet = (48 to 57) union (65 to 90) union (97 to 122)
val i = scala.util.Random.nextInt(alphabet.size)
alphabet(i).toChar
}
Upvotes: 1
Reputation: 128
Something like this will work
def randomAlphaNumericChar(): Char = {
val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toList
scala.util.Random.shuffle(ALPHA_NUMERIC_STRING).head
}
Upvotes: 0