0

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)

2
  • 3
    The exception is really clear. You expect the function to return Char while the method you're using returns Gen[Char]. Fix one of the above. Commented Jul 10, 2016 at 8:50
  • @AvihooMamka Nitpick - It's not an exception, it's a compile time error. Commented Jul 10, 2016 at 11:41

3 Answers 3

1
  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
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Something like this will work

def randomAlphaNumericChar(): Char = {
    val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toList
    scala.util.Random.shuffle(ALPHA_NUMERIC_STRING).head
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.