Reputation: 3099
I am trying to solve combinations task in Scala. I have an array with repeated elements and I have to count the number of combinations which satisfy the condition a+b+c = 0. Numbers should not be repeated, if they are in different places it doesn`t count as a distinct combination. So I turned my array into Set, so the elements would not repeat each other. Also, I have found about combinations method for sequences, but I am not really sure how to use it in this case. Also, I do not know where t put these permutations condition. Here is what I have for now:
var arr = Array(-1, -1, -2, -2, 1, -5, 1, 0, 1, 14, -8, 4, 5, -11, 13, 5, 7, -10, -4, 3, -6, 8, 6, 2, -9, -1, -4, 0)
val arrSet = Set(arr)
arrSet.toSeq.combinations(n)
I am new to Scala, so I would be really grateful for any advice!
Upvotes: 0
Views: 259
Reputation: 1905
Here's what you need:
arr.distinct.combinations(3).filter(_.sum == 0).size
where:
distinct
removes the duplicatescombinations(n)
produces combinations of n
elementsfilter
filters them by keeping only those whose sum is 0size
returns the total number of such combinationsP.S.: arr
don't need to be a var
. You should strive to never use var
in Scala and stick to val
as long as it's possible.
Upvotes: 3