0

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!

Cassie
  • 2,941
  • 8
  • 44
  • 92
  • did you check https://stackoverflow.com/questions/13109720/how-to-create-all-possible-combinations-from-the-elements-of-a-list? – Ramesh Maharjan Nov 06 '17 at 12:51
  • I did. But I need to get combinations by some predicate, not all possible. So it wasn't really helpful – Cassie Nov 06 '17 at 13:01

1 Answers1

3

Here's what you need:

arr.distinct.combinations(3).filter(_.sum == 0).size

where:

  • distinct removes the duplicates
  • combinations(n) produces combinations of n elements
  • filter filters them by keeping only those whose sum is 0
  • size returns the total number of such combinations

P.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.

lambdista
  • 1,850
  • 9
  • 16