Marcin Wisniowski
11/10/2019, 11:49 AMn
elements of a list are the same? Currently I have list.takeLast(n).toSet().size == 1
but I think this could be simpler.Kroppeb
11/10/2019, 12:08 PMtoSet()
won't stop once it finds an element that is different and will use O(n)
space.Marcin Wisniowski
11/10/2019, 12:14 PMlist.takeLast(n).all { it == list.last() }
is better.Kroppeb
11/10/2019, 12:15 PMmolikuner
11/10/2019, 1:51 PMlist.takeLast(n).dropLast(1).all { it == list.last() }
todd.ginsberg
11/10/2019, 2:26 PMlist.takeLast(n).distinct().size == 1
seems like a nice way to express it.karelpeeters
11/10/2019, 2:38 PMtoSet()
for no reason, distinct() = toSet().toList()
todd.ginsberg
11/10/2019, 2:39 PMpablisco
11/10/2019, 8:30 PMall
to something like:
fun <T> List<T>.all(from: Int = 0, f: (T, T) -> Boolean): Boolean {
for(i in from until (size-1)) if(!f(get(i), get(i + 1))) return false;
return true
}
Highly efficient (although not pretty). Then you can use it like:
list.all(from = n) { a, b -> a == b }
I personally would go with the distinct solution if efficiency is not an issue. This is just a different option.Derek Peirce
11/11/2019, 1:26 AM!list.takeLast(n).asSequence().distinct().drop(1).any()
, the laziness of sequences will prevent any unnecessary comparisons, and will only store as much as is necessary.