[英]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. 希望您做得很好,我刚刚开始使用scala基本编程,我想使用foreach或您认为是最佳方法的其他东西生成一些字符串变量。
How do I use scala.util.Random
to generate this result: 如何使用
scala.util.Random
生成此结果:
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: 因此基本上从1A到1J可能是这样的:
Var 1A = "B"
Var 1B = "G"
Var 1C = "A"
Var 1D = "D"
Var 1E = "H"
and so on until 1J
The simplest way is probably to use Random.shuffle
. 最简单的方法可能是使用
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.) (请注意,
1A
不是有效的Scala标识符,而Val
是无效的语法。)
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: 您可以使用Random软件包中的
shuffle
:
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. 如果愿意,可将结果分配给变量列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.