First, there is the straight-forward translation of what you have to something more functional: get all pairs, filter by divisibility (untested).
(no need for n, that’s just ar.length)
def divisibleSumPairs(k: Int, ar: Array[Int]): Int = {
** val indices = 0 until ar.length**
** indices.flatMap(i => indices.map(j => (i, j))).filter{ case (i, j) =>
i < j && (ar(i) + ar(j)) % k == 0
}.size**
}
That’s functional, but not very efficient. More efficient would be to count how often each value for (ar(i) % k) appears and calculate the result (untested):
def divisibleSumPairs(k: Int, ar: Array[Int]): Int = {
** val moduloCounts = ar.groupBy(_ % k).mapValues(_.size).view.force**
** val keys = moduloCounts.keySet**
** keys.flatMap(key1 => keys.map(key2 => (key1, key2))).map { case (key1, key2) =>**
** if(key1 == key2) {**
** val moduloCount = moduloCounts(key1)**
__ moduloCount*(moduloCount - 1)__
** } else {**
__ moduloCounts(key1)*moduloCounts(key2)__
** }**
** }.sum**
}
I haven’t tested the code above, so there may be bugs, but this shows how it can be done.
Best, Oliver