alex cole
12/17/2020, 5:49 AMmineLocation = Set<Int>(mineCount) { Random.nextInt(0, length * width)}
Platon Malyugin
12/17/2020, 6:06 AMalex cole
12/17/2020, 6:18 AMvar mineLocations = arrayListOf<Int>()
while(mineCount != minesSet) {
val i = Random.nextInt(0, length * width)
if (!mineLocations.contains(i)) {
mineLocations.add(i)
minesSet++
}
}
Platon Malyugin
12/17/2020, 6:33 AMval rands = mutableSetOf<Int>()
val mineCount = 10
while (rands.size != mineCount) {
rands.add(Random.nextInt())
}
// return immutable set
rands.toSet()
Platon Malyugin
12/17/2020, 6:34 AMalex cole
12/17/2020, 6:40 AMPlaton Malyugin
12/17/2020, 6:49 AMmickeelm
12/17/2020, 7:29 AMmineCount
? That's not obvious to me since that parameter is not used...and where is length
and width
stated?
Also, Set
is as pointed out before a data structure that only contains uniqiue elements. Moreover, it is by default unordered so there's no need of randomizing heremickeelm
12/17/2020, 7:38 AMval width = 10
val height = 10
val size = width * height //I mean, shouldn't this be a grid (2d-array or so), rather than the product of two numbers?
//This is really all you need. The randomization seems completely unnecessary to me, but maybe I don't understand the use case?
(0..size).toSet()
Matteo Mirk
12/17/2020, 7:49 AMval mineLocation = generateSequence { Random.nextInt(0, length * width) }
.distinct()
.take(mineCount)
.toSet()
mickeelm
12/17/2020, 7:51 AMMatteo Mirk
12/17/2020, 7:51 AMmickeelm
12/17/2020, 7:51 AMMatteo Mirk
12/17/2020, 7:51 AMMatteo Mirk
12/17/2020, 7:54 AMinline fun <T> Set(size: Int, init: () -> T): Set<T> = ...
alex cole
12/17/2020, 7:41 PMMatteo Mirk
12/18/2020, 9:25 AMList(Int, (Int) -> T))
definition from standard lib: this small optimization will let the compiler inline the init
lambda when creating the Set and the Set function itself at the call site, to avoid creating a function objectMatteo Mirk
12/18/2020, 9:26 AMinline
modifier, don’t worry