从Scala中的元素列表中获取多个唯一的随机元素

在Scala中列出

该列表是相同数据类型的元素的不可变集合。使List与数组不同的是List是Linked List。

如何获得多个独特元素?

多个随机唯一元素是一组元素(多个),它们是从列表的唯一元素中随机抽取的随机元素。

示例

    List = (10, 20, 10, 40, 10, 70, 20, 90)
    Distinct elements of list = (10, 20, 40, 70, 90)
    Multiple random elements(2) = (40, 90)

程序查找多个随机唯一元素

object MyObject {
    
    def main(args: Array[String]) {
        val mylist = List(10, 20, 10, 40, 10, 20, 90, 70)
        println("Element of the list:\n" + mylist)
        println("Unique elements of the list:\n" + mylist.distinct)
        println("Multiple Random elmenets of the list:\n" + scala.util.Random.shuffle(mylist.distinct).take(2))
    }
    
}

输出结果

Element of the list:
List(10, 20, 10, 40, 10, 20, 90, 70)
Unique elements of the list:
List(10, 20, 40, 90, 70)
Multiple Random elmenets of the list:
List(20, 90)

说明:

在此程序中,我们将从列表中提取多个唯一的随机元素。为此,我们使用了3个功能,让我们一一讨论。

  • 区别:区别方法完全按照其名称的含义进行操作,即,它剔除重复的元素,而新列表将仅包含唯一的元素。

  • 随机播放:随机播放方法是Random类的一部分,可以将列表中的元素随机排列为随机排列。

  • take:take方法用于从列表中获取任意数量的元素。

因此,要从列表中提取我们的多个唯一随机元素,我们首先使用了distance来提取所有唯一元素。此后,我们使用shuffle对该元素进行了shuffle。因此,在获取元素时,我们将获得随机元素。最后,我们采用了从列表中选择2个元素的方法。