mop mop -4 years ago 109
Scala Question

get one random letter from each tuple then return them all as a string

3 tuples in a list

val l = List(("a","b"),("c","d"),("e","f"))


choice one element from each tuple then return this 3 letters word every time

for example: fca or afd or cbf ...

how to realize it

the same as:

echo {a,b}{c,d}{e,f}|xargs -n1|shuf -n1|sed 's/\B/\n/g'|shuf|paste -sd ''

Answer Source

Working with tuples can be a bit of a pain. You can't easily index them and tuples of different sizes are considered different types in the type system.

val ts = List(("a","b"),("c","d"),("e","f"))
val str = ts.map{t =>
  t.productElement(util.Random.nextInt(t.productArity))
}.mkString("")

Every time I run this I get a different result: bde, acf, bdf, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download