Skip to content

Commit

Permalink
Merge pull request #74 from andreas-roehler/master
Browse files Browse the repository at this point in the history
solution2.5.2.6.scala provided
  • Loading branch information
winitzki authored Nov 28, 2024
2 parents bf0f565 + 2f791de commit 9a4a6f2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
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))

0 comments on commit 9a4a6f2

Please sign in to comment.