To create a set of size N in Kotlin, you can use the generateSequence
function to generate a sequence and then convert it to a set using the toSet
method.
In this example,
import kotlin.sequences.generateSequence
.createSetOfSizeN
that takes an integer n
as a parameter. This parameter represents the desired size of the set.generateSequence
function to generate a sequence of numbers starting from 1. The take
method is used to limit the sequence to n
elements.toSet
method. This ensures that the resulting collection is a set with exactly n
unique elements.main
function, we call createSetOfSizeN
with a specific size (e.g., 5) and store the result in a variable named mySet
.println
function.import kotlin.sequences.generateSequence
fun createSetOfSizeN(n: Int): Set<Int> {
return generateSequence(1) { it + 1 }.take(n).toSet()
}
fun main(args: Array<String>) {
val mySet = createSetOfSizeN(5)
println("Created set of size 5: $mySet")
}
Created set of size 5: [1, 2, 3, 4, 5]
In this example,
import kotlin.random.Random
.createRandomSetOfSizeN
that takes an integer n
as a parameter. This parameter represents the desired size of the set.resultSet
to store the unique random numbers.while
loop to repeatedly add random numbers to the set until its size equals n
. The Random.nextInt
function generates random integers.main
function, we call createRandomSetOfSizeN
with a specific size (e.g., 5) and store the result in a variable named myRandomSet
.println
function.import kotlin.random.Random
fun createRandomSetOfSizeN(n: Int): Set<Int> {
val resultSet = mutableSetOf<Int>()
while (resultSet.size < n) {
resultSet.add(Random.nextInt(1, 100))
}
return resultSet
}
fun main(args: Array<String>) {
val myRandomSet = createRandomSetOfSizeN(5)
println("Created set of size 5 with random numbers: $myRandomSet")
}
Created set of size 5 with random numbers: [12, 47, 85, 24, 37]
In this tutorial, we learned How to create a Set of size N in Kotlin language with well detailed examples.