Sales by Match (Hackerank) solved using Kotlin
Problem
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
Example
There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is.
Function Description
Complete the sockMerchant function in the editor below.
sockMerchant has the following parameter(s):
- int n: the number of socks in the pile
- int ar[n]: the colors of each sock
Returns
- int: the number of pairs
Input Format
The first line contains an integer, the number of socks represented in.
The second line contains space-separated integers, the colors of the socks in the pile.
Sample Input
STDIN Function
----- --------
9 n = 9
10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
Sample Output
3
Explanation
There are three pairs of socks.
Solution
From the explanation, we need to get the pairs of duplicated values in the array.
Note: if the pair is 3 it will be counted as 1
Sample array
val ty = arrayOf(10, 20, 20, 10, 10, 30, 50, 10, 20)
First Step: is to get the list of duplicated value and their count.
you will use “groupBy” to get the group of each element
val mapva = ty.groupBy { it }
Result: {10=[10, 10, 10, 10], 20=[20, 20, 20], 30=[30], 50=[50]}
Then you use the “mapValues” to create a “Map”get the count of each value as key and value
val mapval = ty.groupBy { it } .mapValues { it.value.count() }
Result: {10=4, 20=3, 30=1, 50=1}
Second Step: Create a variable that will hold the count of duplicated value
var sock_count = 0for (u in mapval) {
if (u.value >= 2) {
sock_count += u.value / 2}
}
loop through the values in the Map, check if any value is greater than or equal to 2 if yes divide them by 2, and add them to the “sock_count” variable.
Third Step: Print the “sock_count”.
Cheers 🥳🥳🥳🥳🥳🥳🥳
Thanks for reading.