Scala随机字符串 [英] Scala Random String

查看:535
本文介绍了Scala随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望您做的很好,我刚刚开始进行scala基本编程,我想使用foreach或一些您认为是最好的方法来生成一些字符串变量.

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.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

所以基本上从1A到1J可能是这样的:

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

推荐答案

最简单的方法可能是使用Random.shuffle.

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)

然后随机播放它们:

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

(请注意,1A不是有效的Scala标识符,Val是无效的语法.)

(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.

这篇关于Scala随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆