Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
Is there a more elegant way or a shorter one of turning a list element to int, incrementing it and turning it back to string?

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()
        }
    }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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"))}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda