https://kotlinlang.org logo
Title
s

skendrick

09/30/2019, 3:39 PM
I’m trying to count the diffs in two equal-lengthed strings. My approach is to reduce one string into an int, using the index to compare chars in the other string. Maybe I’m just thinking about this too much like JS?
str1 = "ABC"
str2 = "ABB"
diff = 1
// JS
str1.reduce((accumulator, currLetter, index) => {
      if (currLetter !== str2[index])  return accumulator + 1
}, 0)
Is this a kotlin-y way to approach the problem or am I being a dingus?
s

Shawn

09/30/2019, 3:41 PM
you can do pretty much exactly this with
foldIndexed {}
!
s

skendrick

09/30/2019, 3:43 PM
Cool! I definitely discovered that method, but I’m confused as to the implementation:
Intellij seems mad at me, though I think I’m satisfying the method’s signature correctly?
p

Pavlo Liapota

09/30/2019, 3:45 PM
val str1 = "ABCDF"
val str2 = "ABBEF"
val diffs = str1.zip(str2)
    .count { (ch1, ch2) -> ch1 != ch2}
s

Shawn

09/30/2019, 3:48 PM
@skendrick (hopefully tagged the right one 😬), you’re gonna wanna brush up on your lambda syntax - the call’s gonna look something more like this:
str1.foldIndexed(initial = 0) { index, acc, char ->
    if (char != str2[index]) acc + 1 else  acc
}
@Pavlo Liapota’s zip solution is also pretty nifty, though I’d probably give it its own named extension method
s

skendrick

09/30/2019, 3:55 PM
Ahhh, thanks, y’all! Wow, I think I mixed up Java lambda syntax a bit. tyty for the feedback!
👍 1
:kotlin: 🤘
I’ll update my name to make tagging easier 😆
💯 1