Scala Random String

2019-03-06 19:48发布

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

标签: scala random
2条回答
Luminary・发光体
2楼-- · 2019-03-06 20:08

You can use shuffle from Random package:

scala> scala.util.Random.shuffle(('A' to 'J').toList map (_.toString))
res2: List[String] = List(C, F, D, E, G, A, B, I, H, J)

Assign the result to the list of variables if you like.

查看更多
Bombasti
3楼-- · 2019-03-06 20:22

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.

查看更多
登录 后发表回答