Scala Random String

懵懂的女人 提交于 2019-12-02 14:03:55

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!