I’m trying to count the diffs in two equal-lengthe...
# getting-started
s
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?
Copy code
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
you can do pretty much exactly this with
foldIndexed {}
!
s
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
Copy code
val str1 = "ABCDF"
val str2 = "ABBEF"
val diffs = str1.zip(str2)
    .count { (ch1, ch2) -> ch1 != ch2}
s
@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:
Copy code
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
Ahhh, thanks, y’all! Wow, I think I mixed up Java lambda syntax a bit. tyty for the feedback!
👍 1
K metal
I’ll update my name to make tagging easier 😆
💯 1