This function returns the number of pairs of the same elements in the array
It takes, array length and the array as the parameter
n: Length of array
ar: Array of integers for example
4 6 7 8 7 6 6 7 6 4
returns 4
fun getNumberOfPairs(n: Int, ar: Array<Int>): Int {
val enteries = HashSet<Int>()
var pairs = 0
for (i in 0 until n) {
if (!enteries.contains(ar[i])) {
enteries.add(ar[i])
} else {
pairs++
enteries.remove(ar[i])
}
}
println(pairs)
return pairs
}
How can we write this code in a better way for readability/performance?
1 Answer 1
Overall it's very readable and fast already. Good job.
I have some suggestions for possible improvements:
- As
n
must be equal toar.size
, you could drop that parameter from the method and usear.size
in place ofn
within the method body. - This method is a pure function except for the side effect of printing the result. Being a "pure function" is often a good thing so you can move the printing of the result to outside the method. Printing something is also quite time-consuming.
- Your method could easily support more than
Int
, it doesn't have to be restricted by a specific type. You could check for duplicates of any type so we can make this method generic. - As you are iterating over elements you could use
for (e in ar)
instead of iterating over the indexes withfor (i in 0 until n)
. This would make it more efficient for data structures that doesn't have a \$O(1)\$ lookup-time, for exampleLinkedList
. - The method
HashSet.add
returnsfalse
if the value already exists, so you don't need the call to.contains
. - There is a typo in the name
enteries
, it should be calledentries
. ar
could be calledinput
to make it more readable.
After applying all of the above, this is what you would end up with:
fun <T> getNumberOfPairs(input: Array<T>): Int {
val entries = HashSet<T>()
var pairs = 0
for (e in input) {
if (!entries.add(e)) {
pairs++
entries.remove(e)
}
}
return pairs
}