Deden Bangkit Deden Bangkit - 13 days ago 4x
Scala Question

Scala Random String

Hope you are doing good, I just started scala basic programming, I want to generate some string variable with foreach or something else you think is the best method.

How do I use

to generate this result:

Var 1A:String = random between A to J
Var 1B:String = random between A to J but not 1A value
Var 1C:String = random between A to J, not 1A and not 1B
Var 1D to 1J also should have different random value from A to J

So basically from 1A to 1J could be like this:

Var 1A = "B"
Var 1B = "G"
Var 1C = "A"
Var 1D = "D"
Var 1E = "H"
and so on until 1J

Your guys are so mean to me as a newbie programmer :) Thank you


The simplest way is probably to use Random.shuffle.

First construct your list of characters:

scala> val chars = ('A' to 'J').toList
chars: List[Char] = List(A, B, C, D, E, F, G, H, I, J)

Then shuffle them:

scala> val shuffled = scala.util.Random.shuffle(chars)
shuffled: List[Char] = List(C, E, G, B, J, A, F, H, D, I)

Now you've got a list of these ten characters in a random order. If you need variables referring to them, you can do something like this:

scala> val List(a, b, c, d, e, f, g, h, i, j) = shuffled
a: Char = C
b: Char = E
c: Char = G
d: Char = B
e: Char = J
f: Char = A
g: Char = F
h: Char = H
i: Char = D
j: Char = I

(Note that 1A isn't a valid Scala identifier, and Val isn't valid syntax.)

Or you can refer to them by index:

val a = shuffled(0)
val b = shuffled(1)

Or you could just work with them in the list.