Skip to content

Problem 1 [Language]: Multiples of 3 and 5 #14

@eloots

Description

@eloots

How does the solution using Set, as demonstrated in one of the solutions, work ?

Answer:

Scala Sets work as mathematical sets. Every value of a set is unique within that set, i.e. there are no duplicates.

The Scala Set collection defines a number of useful operations that allow you to combine two sets.

For example, taking the union of two sets can be done using the ++ operator.

For example:

val set1 = Set(1,2,3)
val set2 = Set(3,4,5)

val setUnion = set1 ++ set2

println(setUnion)

will print the following:

Set(5, 1, 2, 3, 4)

As can be seen, Sets are unordered. Note that, in case you need an ordered Set, there is an implementation of such an animal in the Scala collection library.

As a bonus, there are other useful operators on Set such as & and &~ as demonstrated here:

scala> set1 & set2
res2: scala.collection.immutable.Set[Int] = Set(3)

scala> set1 &~ set2
res3: scala.collection.immutable.Set[Int] = Set(1, 2)

You should be able to figure out what these do for yourself. Quite powerful these Scala collections...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions