3

Let's say I have an array like this:

val grid = Array(10) { IntArray(10) { 1 } }

And now I want to set some of them to 2 instead. I could do this:

for (i in 0..5) {
    for (j in 0..5) {
        grid[i][j] = 2
    }
}

But what I'd like to do is this:

grid[0..5][0..5] = 2

Is there some faster way to do it like this?

2
  • It seems this is possible for one dimension, by creating an operator function that takes a range (e.g., operator fun IntArray.set(indices: IntRange, value: Int)). However, I can't think of how to make this work for a two-dimensional array. Or, at least, I can't think of an intuitive way to do it (you can define the operator function for the two-dimensional array type, but then it looks like you're accessing a one-dimensional array at first glance). Commented Mar 5, 2022 at 3:42
  • do you really need arrays? it is probably easier to implement something like that if you do not use arrays (or if you do not mix primitive with ~object arrays) Commented Mar 8, 2022 at 12:35

1 Answer 1

3

You can achieve something similar, e.g.:

grid[3..5, 2..4] = 5

by using the following extension function:

operator fun Array<IntArray>.set(outerIndices : IntRange, innerIndices : IntRange, newValue : Int) {
    for (i in outerIndices) {
        for (j in innerIndices) {
            this[i][j] = newValue
        }
    }
}

If you really wanted something like grid[3..5][2..4] = 5 you would then first need to implement a getter for the first IntRange which may hold a ~builder with the actual array reference so that the actual array can be adjusted on the set-call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.