1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
4 IN: rosetta-code.hailstone-sequence
6 ! http://rosettacode.org/wiki/Hailstone_sequence
8 ! The Hailstone sequence of numbers can be generated from a
9 ! starting positive integer, n by:
11 ! * If n is 1 then the sequence ends.
12 ! * If n is even then the next n of the sequence = n/2
13 ! * If n is odd then the next n of the sequence = (3 * n) + 1
15 ! The (unproven), Collatz conjecture is that the hailstone
16 ! sequence for any starting number always terminates.
20 ! 1. Create a routine to generate the hailstone sequence for a
23 ! 2. Use the routine to show that the hailstone sequence for the
24 ! number 27 has 112 elements starting with 27, 82, 41, 124 and
25 ! ending with 8, 4, 2, 1
27 ! 3. Show the number less than 100,000 which has the longest
28 ! hailstone sequence together with that sequences length.
29 ! (But don't show the actual sequence)!
31 : hailstone ( n -- seq )
35 dup even? [ 2 / ] [ 3 * 1 + ] if
40 : hailstone-main ( -- )
42 "The hailstone sequence from 27:" print
43 " has length " write length .
44 " starts with " write 4 head [ unparse ] map ", " join print
45 " ends with " write 4 tail* [ unparse ] map ", " join print
47 ! Maps n => { length n }, and reduces to longest Hailstone sequence.
49 [ [ hailstone length ] keep 2array ]
50 [ [ [ first ] bi@ > ] most ] map-reduce
52 "The hailstone sequence from " write pprint
53 " has length " write pprint "." print ;