The code works just fine, its just ugly to llok at, especially as in my case i have to do that not only previous and next, but upper 3, lower 3 in a 2d list, so it becomes quite verbose. Is there a shorter way of doing this, maybe using "it"?
val nums = mutableListOf("0", "X", "0", "X", "0")
for (num in 0 until nums.size) {
if (nums[num] == "X") {
var a = nums[num - 1]
if ( nums[num - 1] != "X") nums[num - 1] = (nums[num - 1].toInt() + 1).toString()
if ( nums[num + 1] != "X") nums[num + 1] = (nums[num + 1].toInt() + 1).toString()
}
}
Instead of looking for "X" and increasing values around it, you could look for numbers and alter them based on their surrounding values. This way, you can make use of the Iterable<T>.map or Iterable<T>.mapIndexed functions.
For every element, you just have to look at the surrounding amount of values, both before and after the element. One way of doing so, is using List<out E>.subList(fromIndex: Int, toIndex: Int). As far as I understood, the value should be increased for every "X" found in that sublist.
Combining this, you may end up with something along the lines of:
fun increase(numbers: List<String>, surrounding: Int): List<String> {
return numbers.mapIndexed { index, value ->
val intValue = value.toIntOrNull()
?: return@mapIndexed value
val lowerSublistBound = (index - surrounding).coerceAtLeast(0)
val upperSublistBound = (index + surrounding + 1).coerceAtMost(numbers.size)
val increaseBy = numbers.subList(lowerSublistBound, upperSublistBound).count { it == "X" }
"${intValue + increaseBy}"
}
}
It's not shorter per-se but works with an arbitrary amount of surrounding values, instead of hard coding to retrieve the n preceding and following elements.
Using this, yields the following results:
fun main() {
val baseNumbers = listOf("X", "X", "0", "1", "X", "2", "X")
println(increase(baseNumbers, 0) == baseNumbers)
println(increase(baseNumbers, 1) == listOf("X", "X", "1", "2", "X", "4", "X"))
println(increase(baseNumbers, 2) == listOf("X", "X", "3", "3", "X", "4", "X"))
println(increase(baseNumbers, 3) == listOf("X", "X", "3", "5", "X", "4", "X"))
println(increase(baseNumbers, 4) == listOf("X", "X", "4", "5", "X", "5", "X"))
println(increase(baseNumbers, 5) == listOf("X", "X", "4", "5", "X", "6", "X"))}