Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking how many elements a set contains

I need to write a function that returns true if a set (this set is the output of another function) contains 1 element and otherwise it leaves the set as it is.

For example:

Set(1) returns a specific result and Set(2,4) returns the set as it is.

How can I check how many elements a set contains?

like image 334
user2947615 Avatar asked Nov 30 '13 20:11

user2947615


People also ask

How do you determine the number of elements in a set?

The formula n(A U B) = n(A) + n(B) - n(A n B) describes how to count elements in two sets that intersect. We can also use Venn diagrams to help us count elements in sets, and they are especially useful when we are considering more than two sets.

How many elements does the set contain?

A set may have infinitely many elements, so we can't list all of them. For example let E = {all even integers greater than or equal to 1}.


1 Answers

You just need the size method on a Set:

scala> Set(1).size
res0: Int = 1

scala> Set(1,2).size
res1: Int = 2

See also the documentation for Set.

Let's say your other function is called getSet. So all you need to do is call it, then check the size of the resulting Set, and return a value depending on that size. For example, I shall assume that if the set's size is 1, we need to return a special value (a Set containing the value 99) - but just replace this with whatever specific result you actually need to return.

def mySet = {
  val myset = getSet()
  if (myset.size == 1) Set(99)  // return special value
  else myset  // return original set unchanged
}
like image 51
DNA Avatar answered Oct 15 '22 02:10

DNA