https://kotlinlang.org logo
e

Ellen Spertus

10/10/2022, 5:39 PM
I know this algorithm is inefficient if the grid is densely populated, but how could this code be improved without changing the algorithm?
k

Klitos Kyriacou

10/10/2022, 6:04 PM
A do-while loop seems more appropriate to me:
Copy code
var x: Int
        var y: Int
        do {
            x = Random.nextInt(0, NUM_COLS)
            y = Random.nextInt(0, NUM_ROWS)
        } while (isOccupied(x, y))
        place(entity, x, y)
e

Ellen Spertus

10/10/2022, 6:05 PM
Thanks! I didn't realize I could declare a var without initializing it.
k

Klitos Kyriacou

10/10/2022, 6:07 PM
You have to initialize it, but not necessarily at the point of declaration.
e

ephemient

10/10/2022, 6:31 PM
* you have to initialize it before it is used, same as a
val
Copy code
val x: Int
var y: Int
if (Random.nextBoolean()) {
    return
} else {
    x = 1
    y = 2
}
// OK to use x and y here
b

bezrukov

10/10/2022, 7:05 PM
you can write
placeIfEmpty(entity, x, y)
fun which returns true if the entity was added. Then use while or do-while as mentioned above. e.g:
Copy code
do {
    val x = Random.nextInt(NUM_COLS)
    val y = Random.nextInt(NUM_ROWS)
} while(!placeIfEmpty(entity, x, y)
Additionally, you will avoid implicit contract "check it's not occupied before placing"
k

Klitos Kyriacou

10/10/2022, 7:50 PM
That also reminds me that local variables inside a do-while block are visible to the
while
condition expression. Unlike Java.
3 Views