In a compute program, how would I calculate in Kot...
# announcements
t
In a compute program, how would I calculate in Kotlin where the values of a list are all equal to each to each other? Thank you.
e
convert the list to set and check if the size of the set is 1. Assuming that the items in the list are 1) similar type 2) comparable to each other
(or call
.distinct()
with the same assumptions)
e
another option (will short circuit unlike the above):
list.all { it == list.first() }
n
this is a fun codegolf question. I think you could also do something like
.asSequence().zipWithNext().any { a, b -> a != b }
t
@ephemient would this code work:
Copy code
fun numbersEven(data: List<Int>) = data.toSet().size == 1
n
works fine, it's just not the most efficient
e
given your description I would expect empty to be true, and it doesn't match the function name... but yes, it does something
t
@ephemient oh yes.. I will rename this function.
n
oh, another idea --
data.asSequence().distinct().take(2).toList().size == 1
t
@nanodeath thanks for this.
👍 1
e
why not
.all
though? I do mean it, that if the contract is "all values of a list are equal to each other", it should be vacuously true for the empty list
t
@ephemient I have this other question. Is there a way to do this code in a lambda-like way... Instead of looping over and printing words which start with 'z' can we do this in a couple of lines using lambdas? Here is my current code
Copy code
for (string in asList) {
    if (string != asList[asList.size - 1]) {
        if (string[0] == 'Z' || string[0] == 'z') {
            println(string)
        }
    }
}
Apologise if this is a strange question... again, I feel like there is more concise kotlin-like way of doing this
apologies if this question is a bit strange. I am Just getting to know Kotlin.
@ephemient wait never mind Kotlin suggested this for me:
Copy code
asList
    .asSequence()
    .filter { it != asList[asList.size - 1] && (it[0] == 'Z' || it[0] == 'z') }
    .forEach { println(it) }
e
not really Kotlin, just general coding...
Copy code
for (string in asList) {
    if (string != asList.last() && string.isNotEmpty() && string.first() in "Zz") {
        println(string)
    }
}
if you wanted to do it with the Kotlin collections extensions, you could certainly
Copy code
asList.filter { string -> string != asList.last && string.firstOrNull()?.let("Zz"::contains) == true }.forEach(::println)
unless you can guarantee your strings are all non-empty, I would use
.firstOrNull()
because
[0]
will crash on an empty string
t
@ephemient I think this is alright?
Copy code
asList
    .filter { it.isNotEmpty() && (it[0] == 'Z' || it[0] == 'z') }
    .forEach { println(it) }
e
sure, although you've lost the != last check
t
@ephemient what do you mean by this
e
your previous code contained
if (string != asList[asList.size - 1])
which can be simplified to
string != asList.last()
t
@ephemient Oh ok... will do this instead.