I am given a list of strings and I need to see if they are in alphabetical order.
I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.
for (item in array)
println(item[0])
For example ["adam", "ben", "chloe"]
should return true
.
And likewise for ["ben", "adam", "chloe"]
should return false
.
UPD: Since Kotlin 1.2 the following is available:
Most efficient variant, creates the smallest amount of intermediate objects:
listOf(1, 2, 3).asSequence().zipWithNext { a, b -> a <= b }.all { it }
Note on efficiency: Creates only two Sequence
objects and one function object. Uses Boolean
constants as an intermediate value. The final all
invocation is inlined as a while
loop over the sequence.
Slightly less efficient variant:
listOf(1, 2, 3).asSequence().windowed(2).all { (a, b) -> a <= b }
It's slightly less efficient, as it creates creates intermediate List(a, b)
for every element of the original list.
Both of these variants were listed in the answers below by @Billbucket and @AshishChaudhary.
Old answer, for previous versions of Kotlin:
Here is a one liner:
val a = listOf("a", "b", "c")
a.zip(a.drop(1)).all { (a, b) -> a <= b }
// true
Explanation:
a.zip(a.drop(1))
returns pairs of neighbour elements. If in every pair first element is less or equal to the next, array is in order.
If you want to improve performance, you can wrap your array in lazy sequence first. In this case array won't be copied:
a.asSequence().let { it.zip(it.drop(1)).all { (a, b) -> a < b } }
The whole thing is O(N)
(single pass through array), which is optimal for this task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With