scala中随机数_如何在Scala中随机播放(随机)列表?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 18:45   35   0

scala中随机数

改组列表元素 (Shuffling list elements)

Shuffling list elements is randomizing the index of elements of the list. So, list('A', 'B', 'C', 'D') will be shuffled as list('C', 'A', 'D', 'B').

改组列表元素正在随机化列表元素的索引。 因此, list('A','B','C','D')将作为list('C','A','D','B')改组。

To shuffle elements of a list we will be using the shuffle method of the Random class.

要随机播放列表中的元素,我们将使用Random类的shuffle方法。

Syntax:

句法:

    Random.shuffle(list)

The method takes a list and returns a list that has shuffled elements in the list.

该方法获取一个列表,并返回一个列表,该列表中的元素经过改组。

Let's take a few examples to randomize lists in Scala,

让我们举几个例子来随机化Scala中的列表,

Example 1:

范例1:

import scala.util.Random

object MyClass {
    
    def main(args: Array[String]) {
        val list = List('A', 'B', 'C', 'D', 'E')
        println("The list: " + list)
        println("Shuffling list elements...")
        println("Shuffled list: " + Random.shuffle(list))
    }
    
}

Output

输出量

RUN 1:
The list: List(A, B, C, D, E)
Shuffling list elements...
Shuffled list: List(A, B, E, C, D)

RUN 2:
The list: List(A, B, C, D, E)
Shuffling list elements...
Shuffled list: List(E, D, A, B, C)

Explanation:

说明:

Here, we have created a list of characters and then used the shuffle method to randomize the elements of the list.

在这里,我们创建了一个字符列表,然后使用shuffle方法将列表中的元素随机化。

Example2: Creating a list using range and shuffling it.

示例2:使用范围创建列表并将其改组。

import scala.util.Random

object MyClass {
    
    def main(args: Array[String]) {
        val list = List.range(5, 10)
        println("Shuffling list elements within range 5 to 10...")
        println("Shuffled list : " + Random.shuffle(list))
    }
    
}

Output

输出量

RUN 1:
Shuffling list elements within range 5 to 10...
Shuffled list : List(6, 9, 8, 7, 5)

RUN 2:
Shuffling list elements within range 5 to 10...
Shuffled list : List(5, 8, 9, 6, 7)

Explanation:

说明:

Here, we have used the range method of the list to create a list within values given in the range and then used the shuffle method of Random class to shuffle list elements.

在这里,我们使用列表的range方法在该范围内给定的值内创建一个列表,然后使用Random类的shuffle方法对列表元素进行排序。

翻译自: https://www.includehelp.com/scala/how-to-shuffle-randomize-a-list.aspx

scala中随机数

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP