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.6.scala provided #74

Merged
merged 5 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
*RCS*
*.class
*.log
chapter02/worksheets/solution2.5.2.5_foldLeft.scala

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
auspack/
befehle.org
hs_err_pid*
target
Expand Down
43 changes: 43 additions & 0 deletions chapter02/worksheets/solution2.5.2.6.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
Exercise 2.5.2.6

In a sorted integer array where no values are repeated, find all
pairs of values whose sum equals a given number 𝑛.
Use tail recursion.

A type signature and a sample test:

def pairs(goal: Int, xs: Array[Int]): Set[(Int, Int)] = ???

scala> pairs(10, Array(1, 2, 4, 5, 6, 8))
res0: Set[(Int, Int)] = Set((2,8), (4,6), (5,5))
*/

def pairsIntern(goal: Int, xs: Array[Int], res: Seq[(Int, Int)] = Seq((0, 0))): Seq[(Int, Int)] = {
if (xs.isEmpty) res.reverse.tail
else {
val a = xs.filter(_ + xs.head == goal)
if (a.isEmpty)
pairsIntern(goal, xs.tail, res)
else {
val b = (xs.head, a(0))
val c = b +: res
pairsIntern(goal, xs.tail, c)
}
}
}

def pairs(goal: Int, xs: Array[Int]): Set[(Int, Int)] = {
pairsIntern(goal, xs).toSet
}

val expected: Set[(Int, Int)] = Set((2,8), (4,6), (5,5))
val result = pairs(10, Array(1, 2, 4, 5, 6, 8))
assert(result == expected)

// scala> :load solution2.5.2.6.scala
// :load solution2.5.2.6.scala
// def pairsIntern(goal: Int, xs: Array[Int], res: Seq[(Int, Int)]): Seq[(Int, Int)]
// def pairs(goal: Int, xs: Array[Int]): Set[(Int, Int)]
// val expected: Set[(Int, Int)] = Set((2,8), (4,6), (5,5))
// val result: Set[(Int, Int)] = Set((2,8), (4,6), (5,5))
Loading