Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package readerwriter
import readerwriter.internal.Writer, Writer._
import util._
object Writers {
/* everything required to use tell and the monad operations
* is already imported */
def collatzDepth(n: Int): Writer[List[String], Int] = ???
def collatzSearch(start: Int, limit: Int): Writer[List[String], Int] = ???
}
object CollatzWithoutWriter {
def collatzDepth(n: Int): (List[String], Int) =
if (n == 1)
(List("got 1, doing nothing"), 0)
else if (n % 2 == 0) {
val (way, depth) = collatzDepth(n / 2)
(s"got $n, halving" :: way, depth + 1)
} else {
val (way, depth) = collatzDepth(n * 3 + 1)
(s"got $n, tripling plus one" :: way, depth + 1)
}
def collatzSearch(start: Int, limit: Int): (List[String], Int) = {
val (way, depth) = collatzDepth(start)
if (depth < limit) {
val (way2, number) = collatzSearch(start + 1, limit)
(s"testing $start" :: way ++ (s"depth was $depth" :: way2), number)
} else
(s"testing $start" :: way ++ List(s"depth was $depth", s"returning $start"), start)
}
}