Scala:如何获取给定列表的随机元素形式

时间:2016-07-10 07:49:31

标签: scala random

我想从给定列表中选择随机元素:

public class NegateBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !(bool) value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

所以目前这个编译:

  

类型不匹配;发现:org.scalacheck.Gen [Char] required:Char       Gen.oneOf(ALPHA_NUMERIC_STRING)

3 个答案:

答案 0 :(得分:1)

  def randomAlphaNumericChar(): Char = {
  /*
     ASCII Codes
     [0-9]: (48 to 57)
     [A-Z]: (65 to 90)
     [a-z]: (97 to 122)
  */
    val alphabet = (48 to 57) union (65 to 90) union (97 to 122)
    val i = scala.util.Random.nextInt(alphabet.size)
    alphabet(i).toChar
  }

答案 1 :(得分:1)

对于

val xs = ('a' to 'z') ++ ('A' to 'Z') ++ (1 to 9)

xs.maxBy(_ => scala.util.Random.nextInt)

这里maxBy将一个函数应用于集合的每个元素,然后选择应用于每个元素的函数返回的最大值。在这种情况下,函数是从Random.nextInt返回的随机值。

答案 2 :(得分:0)

这样的东西会起作用

def randomAlphaNumericChar(): Char = {
    val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toList
    scala.util.Random.shuffle(ALPHA_NUMERIC_STRING).head
}