Ray Rahke
03/08/2024, 5:17 PMJacob
03/08/2024, 5:23 PMJoffrey
03/08/2024, 5:24 PMJacob
03/08/2024, 5:26 PMJacob
03/08/2024, 5:28 PMRay Rahke
03/08/2024, 5:29 PMRay Rahke
03/08/2024, 5:29 PMRay Rahke
03/08/2024, 5:29 PMJoffrey
03/08/2024, 5:31 PMfor
is just a higher-level convenience, but you can simply use a local variable and a while loop if you have uncommon needsRay Rahke
03/08/2024, 5:31 PMfun findConsecutiveXs(string: String): Int {
var count = 0
for (i in 0..string.length) {
if (string[i] == 'x') {
for (j in i + 1..string.length) {
if (string[j] == 'x') {
count += 1
} else {
i = j + i; break
}
}
}
}
}
Ray Rahke
03/08/2024, 5:32 PMi
Ray Rahke
03/08/2024, 5:32 PMJacob
03/08/2024, 5:33 PMKlitos Kyriacou
03/08/2024, 5:34 PMfor
loop is just a glorified while
loop. It has a starting value, a condition and a statement that is executed at the end of each iteration. In Kotlin, if that's what you want to do, you do it with a while
loop.
On the other hand, Kotlin for
loops are actually more like Java enhanced for loops ("foreach loops"). for (i in 1..n)
is conceptually similar to for (element in collection)
. In both cases, i
iterates through elements of an Iterable - be it an IntRange or a List. That's why it doesn't make sense to reassign i
to some arbitrary value.Ray Rahke
03/08/2024, 5:34 PMRay Rahke
03/08/2024, 5:35 PMi
jump ahead by an arbitrary amountRay Rahke
03/08/2024, 5:36 PMRay Rahke
03/08/2024, 5:36 PMcontinue
7 times in a rowRay Rahke
03/08/2024, 5:36 PMJoffrey
03/08/2024, 7:26 PMfun findConsecutiveXs(string: String): Int {
var seenX = false
var count = 0
for (c in string) {
if (c == 'x') {
if (seenX) {
count++
} else {
seenX = true
}
} else {
seenX = false
}
}
return count
}
Joffrey
03/08/2024, 7:27 PMfun countConsecutiveXs(string: String): Int =
string.zipWithNext().count { (c1, c2) -> c1 == 'x' && c2 == 'x'}
Joffrey
03/08/2024, 7:28 PMKlitos Kyriacou
03/11/2024, 9:46 AMJoffrey
03/11/2024, 1:15 PM