Reputation: 8851
I have an ArrayList
like this :
var amplititudes : ArrayList<Int> = ArrayList()
I want to populate this with random Ints. How can I do this?
Upvotes: 14
Views: 16154
Reputation: 1465
import kotlin.random.Random
fun main() {
// creates an instance of ArrayList<Int!>
val list = ArrayList(List(10) { Random.nextInt() })
}
Verified on Kotlin v2.0.20
Upvotes: 0
Reputation: 29864
Since Kotlin 1.3 was released there is no need to use Java's java.util.Random
which would restrict your code to the JVM. Instead kotlin.random.Random
was introduced which is available on all platforms that support Kotlin.
val 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).
Upvotes: 5
Reputation: 5162
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 (OUTDATED!)
You no longer need to do this, as Kotlin will only create a single instance of Random.
As suggested in the comment instead of creating an instance of Random
each time it is better to initialize it once:
var ran = Random()
var amplititudes = (1..10).map { ran.nextInt() }
Upvotes: 21
Reputation: 60046
Based to the answer of @Md Johirul Islam You can also use :
val from = 0
val to = 11
val 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
Upvotes: 6
Reputation: 2438
At this time, is not specified in your question the range of the Ints and how many do you need.
So I restrict the case to [n,m] interval, and I suppose you want all the m-n+1 elements.
Taking advantage of method shuffle of ArrayList,
var shuffledList = ArrayList((n..m).toList())
shuffledList.shuffle()
Upvotes: 0
Reputation: 55
To generate a random number of specified length of List and between certain limits, use:
val rnds = (1..10).map { (0..130).random() }
Where (1..0)
-> return list of 10 items
(0..130)
-> return random number between given range
Upvotes: 1
Reputation: 82027
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()
}
Upvotes: 4