Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an Array of strings is sorted in alphabetical order or not using Kotlin?

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.

like image 678
JoelArmstrong Avatar asked Nov 14 '17 22:11

JoelArmstrong


1 Answers

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.

like image 118
Aivean Avatar answered Sep 28 '22 02:09

Aivean