4
\$\begingroup\$

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?

\$\endgroup\$
3
\$\begingroup\$

Overall it's very readable and fast already. Good job.

I have some suggestions for possible improvements:

  • As n must be equal to ar.size, you could drop that parameter from the method and use ar.size in place of n 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 with for (i in 0 until n). This would make it more efficient for data structures that doesn't have a \$O(1)\$ lookup-time, for example LinkedList.
  • The method HashSet.add returns false 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 called entries.
  • ar could be called input 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
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.