Edgar Avuzi
07/17/2025, 8:04 PMEdgar Avuzi
07/17/2025, 8:04 PMclass Solution {
fun imageSmoother(image: Array<IntArray>): Array<IntArray> {
val neighborsOf = { i: Int, j: Int ->
sequence {
for (di in -1..1)
for (dj in -1..1)
image.getOrNull(i + di)
?.getOrNull(j + dj)
?.let { yield(it) }
}
}
return Array(image.size) { i ->
IntArray(image[0].size) { j ->
val neighbors= neighborsOf(i, j)
neighbors.sum() / neighbors.count()
}
}
}
}
I'm considering denesting the neighborsOf
. Here's the nested block I'm referring to:
val neighborsOf = { i: Int, j: Int ->
sequence {
for (di in -1..1)
for (dj in -1..1)
image.getOrNull(i + di)
?.getOrNull(j + dj)
?.let { yield(it) }
}
}
Is denesting even worth it in this context? Or is the current form already clear enough?Edgar Avuzi
07/17/2025, 8:06 PMCLOVIS
07/17/2025, 8:43 PM?.let
is for non-important side effects of an operation, this should probably be a regular if
to improve readability
Also, the return type isn't used, so if you really want to use a scope function here, it should be ?.also
CLOVIS
07/17/2025, 8:45 PMval d = sequenceOf(-1, 0, 1)
fun neighborsCoordinatesOf(i: Int, j: Int): Sequence<Pair<Int, Int>> =
sequenceOf(i to j)
.flatMap { (x, y) -> d.map { x to (y + it) } }
.flatMap { (x, y) -> d.map { (x + it) to y } }
fun neighborsOf(i: Int, j: Int) =
neighborsCoordinatesOf(i, j)
.map { (x, y) -> image.getOrNull(x, y) }
CLOVIS
07/17/2025, 8:45 PM.flatMap
to avoid nestingEdgar Avuzi
07/17/2025, 9:09 PM?.let is for non-important side effects
- is there an article or doc with reasoning around this?joseph_ivie
07/18/2025, 5:49 AMlet
is just a tool to do concatenative programming. I use it that way all the time and haven't seen any advice to the contrary until now.
Also, as an aside, in real life a Array<IntArray>
would be a terrible way to work with image data. A ByteArray
if you want raw pixel data access would make more sense in terms of efficiency, or at least RAM usage. Gotta fill the spec LeetCode gives you, though.Klitos Kyriacou
07/18/2025, 8:46 AM?.also
, but not for ?.let
.CLOVIS
07/18/2025, 8:47 AM?.let
is non-important data conversions. My point was, there shouldn't really be a yield
in a let
joseph_ivie
07/18/2025, 7:12 PMlet
.