I have an array like that:
val list = listOf("cat", "dog", "tac", "atc")
I would like to create from it a new array with strings consist of the same latter.
Result should be a new array without "dog".
Does Kotlin have function for that ? I was testing equal, compare and so on. I didn't find that.
CodePudding user response:
It sounds like you want to group the entries by the set or ordered list of their chars and then find the biggest group.
list.groupBy {
it.toSet()
}.values.maxByOrNull {
it.size
}
or
list.groupBy {
it.toList().sorted()
}.values.maxByOrNull {
it.size
}
The first will include strings which contain repetitions of char(s) to the resultant list e.g. "cat", "caat", "ttacccat". The second is stricter and will only allow strings with exactly the same chars (in any order).
As someone has mentioned, this will only work for inputs where the list of strings you want returned is the largest after you perform the grouping.
CodePudding user response:
val list = listOf("cat", "dog", "tac", "atc")
val result = list
.map { it.toCharArray().sorted().joinToString("") to it }
.groupBy { it.first }
.map { it.value.map { pair -> pair.second } }
.groupBy { it.count() }
.maxByOrNull { it.key }!!
.value
.flatten() // remove this line if there is the possibility
// of more than one result, like in:
// "cat", "dog", "tac", "atc", "dgo", "god", "abc"
println(result) // Output: [cat, tac, atc]