Answer the question
In order to leave comments, you need to log in
How to find duplicates in an array and output?
There is an array of strings - ("C", "A", "B", "B", "G", "A", "C", "H", "A", "F", "F", " F", "C", "F")
Find the number of duplicates in the original.
The output should be in the form of a list of objects, where the object has two fields - the original letter and an array of duplicates:
С -> С, С
A -> A,A
B -> B
F -> F,F,F
To do this, I go through the entire list and compare the first element with each other, and if there is a match, then I save the duplicate together with the original in a separate object, and remove the duplicate from the list. When we reach the end, we also delete the first element so that we don’t go through the list once again and proceed to the next letters that remain. The remaining letters without duplicates are not added to the final array. Until the original array ends
But instead of the desired result, this output is obtained:
C [C, C]
A [A, A]
B [B]
F [F]
C [C]
data class Result(var orig : String, var dup : MutableList<String>)
val list = mutableListOf("C", "A", "B", "B", "G", "A", "C", "H", "A", "F", "F", "F", "C", "F")
val listResult = mutableListOf<Result>()
while (list.size > 0) {
val tempList = mutableListOf<String>()
tempList.addAll(list)
val result = Result(list[0], mutableListOf())
tempList.forEachIndexed { index, value ->
if (index == 0 && tempList.size > 1) return@forEachIndexed
if (tempList[0] == value) {
result.dup.add(value)
list.removeAt(index)
}
}
if (list.size > 0) list.removeAt(0)
if (result.dup.isNotEmpty()) {
listResult.add(result)
}
}
listResult.forEach {
Log.d("Result", "!!! "+it.orig +" " +it.dup.toString())
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question