https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Alex

02/02/2022, 3:12 PM
Hi Guys i'm hoping someone can guide with the following issue i am having, i am still new and learning Kotlin 1. I am currently doing the following code wars problem(refer to screenshot below) 2. After several days of googling around and experimenting with different collection processing functions(example map,filter etc...), i eventually came to this code
Copy code
val myData= intArrayOf(5,5,5,7,8,8)
    val myData2=intArrayOf(1, 1, 3, 3, 7, 2, 2, 2, 2)
    val myData3=intArrayOf(1, 2, 3, 1, 1, 2, 1, 2, 3, 3, 2, 4, 5, 3, 1)
    val myData4=intArrayOf(20, 37, 20, 21)
    
    val testResult=myData4.asSequence().groupBy { it }.values.toList()
    println(testResult) // [[20, 20], [37], [21]]
3. Now the issue i am having is how do i extract the Occurance of an element from [[20,20],[37],[21]] if N=1, in this case the correct result should be [20,37,21] Kindly reach out to me if my explanation is not clear, thank you
k

Klitos Kyriacou

02/02/2022, 3:55 PM
Aren't you losing the order by doing it this way? For example, if N was 2, you wouldn't know where exactly the second 20 was originally. But the exercise requires you to keep the numbers in the same order. There is a simpler way than what you are doing.
m

Marc Javier

02/02/2022, 3:57 PM
first thing that comes to mind is you could keep track of the element in a Map as a key and have the occurrence as a value starting at 1, so when you iterate through the array, check if it exists in the Map, if false - then add it as key with value of 1 then add to an output list, if true - then check if occurrence is == n, if true - skip appending, if occurrence is less than n then add one to occurrence and append element to output list