How to check if an array of strings is sorted alphabetically or not using Kotlin?

I am assigned a list of strings, and I need to see if they are in alphabetical order.

I know that I need to use a for loop and check the first character of each line, but I do not know how to move from there.

for (item in array)
     println(item[0])

For example, ["adam", "ben", "chloe"]should return true.

And also for ["ben", "adam", "chloe"]should be returned false.

+4
source share
6 answers

UPD: starting with Kotlin 1.2 the following is available:

The most effective option, creates the least number of intermediate objects:

listOf(1, 2, 3).asSequence().zipWithNext { a, b -> a <= b }.all { it }

A slightly less efficient option:

listOf(1, 2, 3).asSequence().windowed(2).all { (a, b) -> a <= b }

, List(a, b) .

@Billbucket @AshishChaudhary .


, Kotlin:

:

val a = listOf("a", "b", "c")
a.zip(a.drop(1)).all { (a, b) -> a <= b }
// true

:

a.zip(a.drop(1)) . , .

, . :

a.asSequence().let { it.zip(it.drop(1)).all { (a, b) -> a < b }  }

O(N) ( ), .

+6

:

array.zipWithNext { s1, s2 -> s1 <= s2 }.all { it }
+3

, , for.

, - , :

fun isAlphabetical(stringsArray: Array<String>): Boolean {
    if (stringsArray.size < 2) return true
    return (1 until stringsArray.size).none { stringsArray[it] <= stringsArray[it - 1] }
}

fun main(args: Array<String>) {
    val testCases = arrayOf(arrayOf("adam", "ben", "chloe"), arrayOf("ben", "adam", "chloe"))

    for(testCase : Array<String> in testCases){
        println("The strings are: ${testCase.joinToString()}")
        if (isAlphabetical(testCase)) {
            println("Strings are in alphabetical order.\n")
        } else {
            println("Strings are not in alphabetical order.\n")        
        }
    }    
}

:

The strings are: adam, ben, chloe
Strings are in alphabetical order.

The strings are: ben, adam, chloe
Strings are not in alphabetical order.

( <=), , 1.

+1

( , ). , , . ( O(n log n) ), :

val test = array.asList() == array.asList().sorted()

:

println(if (array.asList() == array.asList().sorted()) "Strings are in alphabetical order." else "Strings are not in alphabetical order.")
+1

:

val list = listOf("a", "b", "c")
list.windowed(2).none { (a, b) -> a > b }
// true
+1

:)

data class Result(val isInOrder: Boolean, val lastString: String) {
    val toString = when {
        isInOrder -> "Strings are in alphabetical order."
        else -> "Strings are not in alphabetical order."
    }
}

fun Array<String>.isInAlphabeticalOrder() =
    this.fold(Result(true, ""), { acc, word -> Result(acc.isInOrder && acc.lastString < word, word) })

fun main(args: Array<String>) {
    val test1 = arrayOf("adam", "ben", "chloe")
    val test2 = arrayOf("ben", "adam", "chloe")
    println(test1.isInAlphabeticalOrder().toString)
    println(test2.isInAlphabeticalOrder().toString)
}
0

Source: https://habr.com/ru/post/1689280/


All Articles