简体   繁体   English

Kotlin - 创建一个指定长度的随机整数的 ArrayList?

[英]Kotlin - Create an ArrayList of random Integers of specified length?

I have an ArrayList like this :我有一个这样的ArrayList

var amplititudes : ArrayList<Int> = ArrayList()

I want to populate this with random Ints.我想用随机整数填充它。 How can I do this?我怎样才能做到这一点?

One option is to use the array constructor as following:一种选择是使用数组构造函数,如下所示:

var amplititudes  = IntArray(10) { Random().nextInt() }.asList()

Another strategy is:另一种策略是:

var amplititudes  = (1..10).map { Random().nextInt() }

EDIT编辑

As suggested in the comment instead of creating an instance of Random each time it is better to initialize it once:正如评论中所建议的,不要每次都创建一个Random实例,最好初始化一次:

var ran = Random()
var amplititudes  = (1..10).map { ran.nextInt() }

Based to the answer of @Md Johirul Islam You can also use :根据@Md Johirul Islam的回答,您还可以使用:

val from = 0
val to = 11
var random = Random()
var amplititudes  = IntArray(10) { random.nextInt(to - from) +  from }.asList()

in this solution you can specify the range of ints that you want, from 0 to 10 for example在此解决方案中,您可以指定所需的整数范围,例如从 0 到 10

Maybe something like this:也许是这样的:

val amplitudes = ThreadLocalRandom.current().let { rnd ->
    IntArray(5) { rnd.nextInt() }
}

Or this:或这个:

val amplitudes = ThreadLocalRandom.current().let { rnd ->
    (0..5).map { rnd.nextInt() }.toIntArray()
}

Since Kotlin 1.3 was released there is no need to use Java'sjava.util.Random which would restrict your code to the JVM.由于 Kotlin 1.3 已发布,因此无需使用 Java 的java.util.Random将您的代码限制为 JVM。 Instead kotlin.random.Random was introduced which is available on all platforms that support Kotlin.取而代之的是kotlin.random.Random ,它在支持 Kotlin 的所有平台上都可用。

var amplititudes  = IntArray(10) { Random.nextInt() }.asList()

Since you work with a companion object, you don't need to worry about instanting a Random object each iteration (like it was with the Java one that you would have had to put in a variable).由于您使用的是伴随对象,因此您无需担心每次迭代都会实例化一个Random对象(就像使用 Java 时必须放入变量一样)。

To generate a random number of specified length of List and between certain limits, use:要生成指定长度的 List 和某些限制之间的随机数,请使用:

val rnds = (1..10).map { (0..130).random() }

Where (1..0) -> return list of 10 items (0..130) -> return random number between given range其中(1..0) -> 返回 10 个项目的列表(0..130) -> 返回给定范围之间的随机数

At this time, is not specified in your question the range of the Ints and how many do you need.此时,您的问题中未指定 Int 的范围以及您需要多少。

So I restrict the case to [n,m] interval, and I suppose you want all the m-n+1 elements.所以我将 case 限制为 [n,m] 间隔,我想你想要所有 m-n+1 元素。

Taking advantage of method shuffle of ArrayList,利用ArrayList的方法shuffle,

var shuffledList = ArrayList((n..m).toList())
shuffledList.shuffle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM