0

I am trying to write an effective code to reverse Case in kotlin .

HeLLo 5worLD6 -> hEllO 6WORld5 5 and 6 are swap as they have equal difference

Initially I am trying to swap digit's but forEachIndex doesn't change in my existing list . Why?

val uniqueWords = str.split(" ").map { it.toCharArray() }
    uniqueWords.forEachIndexed { index, chars ->
        chars.forEachIndexed { charIndex, c ->
            val endIndex = chars.lastIndex - charIndex
            if(c.isDigit() && chars[endIndex].isDigit()){
                chars[charIndex] = chars[endIndex]
                chars[endIndex] = c
            }
        }
    }

val mVal = uniqueWords // but it doesn't swap integers

Taimoor Khan
  • 541
  • 4
  • 20
  • It's not clear what logic you want to follow for whether two characters should be swapped. Your `endIndex` is the distance between each character and the end which means it points to the character that is the same distance from the center of the string. 5 and 6 are clearly not the same distance from the center of the string in your example. – Tenfour04 Dec 01 '21 at 19:05

1 Answers1

0

Here's your problem:

chars.forEachIndexed { charIndex, c ->
    val endIndex = chars.lastIndex - charIndex

You're iterating over each char/index of each word, and endIndex is a mirror offset right? As charIndex moves from the start to the end, endIndex moves from the end to the start.

So on the first iteration, charIndex = 0 and endIndex = (6 - 0) = 6. Those indices both have digits, so they swap. The array now holds 6WORld5

On the last iteration, charIndex = 6 and endIndex = (6 - 6) = 0. Those indices both have digits, so they swap (again). The array is back to 5WORld6

Every swap is gonna happen twice, because each pair of indices will be checked twice - once with charIndex pointing at the lower index, and once with endIndex pointing at it. If you visualise what you want to happen, it's probably more like the two ends moving towards the middle, and stopping there, right?

cactustictacs
  • 17,935
  • 2
  • 14
  • 25