Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution2.5.2.5.scala #73

Merged
merged 4 commits into from
Nov 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions chapter02/worksheets/solution2.5.2.5.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
Exercise 2.5.2.5
Same task as in Exercise 2.5.2.4 but using a set of sets.

Instead of just three sets a, b, c, we are given a value of type
Set[Set[Int]].

The required type signature and a sample test:

def prodSet(si: Set[Set[Int]]): Set[Set[Int]] = ???

scala> prodSet(Set(Set(1, 2), Set(3), Set(4, 5), Set(6)))
res0: Set[Set[Int]] = Set(Set(1,3,4,6),Set(1,3,5,6),Set(2,3,4,6),Set(2,3,5,6))

Hint: use foldLeft and flatMap.
*/

def prodSetIntern(b: Set[Set[Int]] = Set(Set.empty), symbols: Set[Int] = Set.empty): Set[Set[Int]] = {
if (b.tail.isEmpty) (b.head).map{ x => Set(x) ++ symbols }
else
b.head.flatMap{ x => prodSetIntern(b.tail.toSet, Set(x) ++ symbols) }
}

def prodSet(a: Set[Set[Int]] = Set(Set.empty)): Set[Set[Int]] = {
prodSetIntern(a)
}

val result = prodSet(Set(Set(1, 2), Set(3), Set(4, 5), Set(6)))
val expected: Set[Set[Int]] = Set(Set(1,3,4,6),Set(1,3,5,6),Set(2,3,4,6),Set(2,3,5,6))
assert(result == expected)

// scala> :load solution2.5.2.5.scala
// :load solution2.5.2.5.scala
// def prodSetIntern(b: Set[Set[Int]], symbols: Set[Int]): Set[Set[Int]]
// def prodSet(a: Set[Set[Int]]): Set[Set[Int]]
// val result: Set[Set[Int]] = Set(Set(6, 4, 3, 1), Set(6, 5, 3, 1), Set(6, 4, 3, 2), Set(6, 5, 3, 2))
// val expected: Set[Set[Int]] = Set(Set(1, 3, 4, 6), Set(1, 3, 5, 6), Set(2, 3, 4, 6), Set(2, 3, 5, 6))
Loading