Skip to content

Commit

Permalink
Merge pull request #65 from andreas-roehler/master
Browse files Browse the repository at this point in the history
solution2.5.2.2.scala provided
  • Loading branch information
winitzki authored Aug 24, 2024
2 parents 9f9bebc + b8349de commit 8c4be0d
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chapter02/worksheets/solution2.5.2.2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
Exercise 2.5.2.2
Compute the Collatz sequence 𝑐𝑖 as a stream defined by
𝑐₀ = 𝑛 ;
𝑐 ₖ+₁ =
𝑐ₖ/2 if 𝑐ₖ is even,
3 ∗ 𝑐ₖ + 1 if 𝑐ₖ is odd.
Stop the stream when it reaches 1 (as one would expect5 it will).
*/

def collatzSequence(n: Int, xs: List[Int] = List(0)): List[Int] =
if (xs.head == 1) xs.init
else if (n % 2 == 0)
collatzSequence(n/2, n +: xs)
else collatzSequence (n * 3 + 1, n +: xs)

val expected: List[Int] = List(1, 2, 4, 8)
val result = collatzSequence(8)
assert(result == expected)

// scala> :load solution2.5.2.2.scala
// :load solution2.5.2.2.scala
// def collatzSequence(n: Int, xs: List[Int]): List[Int]
// val expected: List[Int] = List(1, 2, 4, 8)
// val result: List[Int] = List(1, 2, 4, 8)

0 comments on commit 8c4be0d

Please sign in to comment.