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.2.scala provided #65

Merged
merged 5 commits into from
Aug 24, 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
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)
Loading