I decided to make a fun example to demonstrate some of the things we have learned in this series.
The function below tests the Collatz conjecture, calculating a sequence of expressions that—it is conjectured—will always end in 1. Together with the interactive tool that follows it, this function uses:
- An argument (see notebooks 1 and 2)
- A
PatternTest
, to make sure the argument is always an integer greater than 1 (see notebook 1)
- Recursion (see notebook 3)
- Overloading, to ensure the recursion stops (see notebook 3)
Sow
and Reap
, to collect intermediary values (see notebooks 4 and 5)
- A
Manipulate
, to allow one to vary the starting value of the sequence (see notebook 5)
- A
Module
, to localise a variable (see notebook 5)
Function:
ClearAll[collatz];
collatz[n_?(IntegerQ[#] && # > 0 &)] := If[EvenQ[Sow@n], collatz[n/2], collatz[3*n + 1]];
collatz[1] := Sow@1;
Interactive tool:
Manipulate[
Module[
{data = Table[Reap[collatz[n]][[2, 1]], {n, 2, maxN, 1}]},
Row[
{
ListLinePlot[
data,
PlotRange -> {{0, 120}, {0, 10000}},
Frame -> {{True, False}, {True, False}},
FrameLabel -> {"Sequence length", "Sequence values"},
PlotHighlighting -> None,
PlotStyle -> {
Sequence @@
ConstantArray[
Directive[GrayLevel[0.5, 0.5], Thickness[0.001]], maxN - 2],
Directive[Purple, Thickness[0.003]]
},
ImageSize -> 600
],
Framed[
Pane[
Row[Last[data], ","],
ImageSize -> {200, 300},
Scrollbars -> {False, True}
],
RoundingRadius -> 3
]
},
BaseStyle -> "Text"
]
],
{{maxN, 3, "n"}, 3, 100, 1, Appearance -> "Open"},
ContinuousAction -> True
]
Enjoy! :)