oday
07/10/2021, 9:41 PMfor (i in 0 until halfIndex) {
for (j in s.length downTo halfIndex) {
println("i: ${s[i]} j: ${s[j]}")
}
}
s.length / 2
let’s say 5 for example, so the first loop from 0 to 5
and the second from 11 to 5
Sourabh Rawat
07/10/2021, 9:50 PMfor j in s.lastIndex downTo halfIndex
oday
07/10/2021, 9:51 PMSourabh Rawat
07/10/2021, 9:54 PMephemient
07/11/2021, 2:59 AMs[j]
because j = s.length initiallyfor (i in 0 until halfIndex) {
val j = s.lastIndex - i
println("${s[i]} ${s[j]}")
}
or maybe
val forward = s.listIterator()
val backward = s.listIterator(s.size)
while (forward.nextIndex() < backward.previousIndex()) {
println("${forward.next()} ${backward.previous()}")
}
Sourabh Rawat
07/11/2021, 4:01 AMephemient
07/11/2021, 4:03 AM0 until halfIndex
would, but it's a simple tweak to include itSourabh Rawat
07/11/2021, 4:07 AMs.lastIndex
ephemient
07/11/2021, 5:24 AM0 until halfIndex
loop.Sourabh Rawat
07/11/2021, 5:28 AMs.length
thing, then the second loop (correct ver. - s.lastIndex downTo halfIndex
) will take the middle element.ephemient
07/11/2021, 5:57 AM0 until halfIndex
and stepping both in parallel: (0 until halfIndex).zip(lastIndex downTo lastIndex)
will exclude the middle element if oddoday
07/11/2021, 2:51 PMvar j = final.lastIndex
for (i in final.indices) {
if (final[i] != final[j]) {
return false
} else {
j--
}
}
comparing first and last, second and last - 1, etc. no need for halfIndex turns out, wanted to check for palindrome in a certain waySourabh Rawat
07/11/2021, 7:18 PModay
07/11/2021, 7:48 PMephemient
07/11/2021, 8:11 PMfor (i in final.indices) {
if (final[i] != final[final.lastIndex - i]) {
return false
}
}
final.zip(final.reversed()) { a, b ->
if (a != b) {
return false
}
}
oday
07/11/2021, 9:36 PMKlitos Kyriacou
07/13/2021, 9:21 AModay
07/13/2021, 11:59 AM