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 scala.util.Random
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
You can use
shuffle
from Random package:Assign the result to the list of variables if you like.
The simplest way is probably to use
Random.shuffle
.First construct your list of characters:
Then shuffle them:
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:
(Note that
1A
isn't a valid Scala identifier, andVal
isn't valid syntax.)Or you can refer to them by index:
Or you could just work with them in the list.