This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,31 @@
! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
: hailstone ( n -- seq )
[ 1vector ] keep
[ dup 1 number= ]
[
dup even? [ 2 / ] [ 3 * 1 + ] if
2dup swap push
] until
drop ;
<PRIVATE
: main ( -- )
27 hailstone dup dup
"The hailstone sequence from 27:" print
" has length " write length .
" starts with " write 4 head [ unparse ] map ", " join print
" ends with " write 4 tail* [ unparse ] map ", " join print
! Maps n => { length n }, and reduces to longest Hailstone sequence.
1 100000 [a,b)
[ [ hailstone length ] keep 2array ]
[ [ [ first ] bi@ > ] most ] map-reduce
first2
"The hailstone sequence from " write pprint
" has length " write pprint "." print ;
PRIVATE>
MAIN: main

View file

@ -0,0 +1,27 @@
! rosetta/hailstone/length/length.factor
USING: assocs kernel io math math.ranges prettyprint
rosetta.hailstone sequences ;
IN: rosetta.hailstone.length
<PRIVATE
: f>0 ( object/f -- object/0 )
dup [ drop 0 ] unless ;
: max-value ( pair1 pair2 -- pair )
[ [ second ] bi@ > ] most ;
: main ( -- )
H{ } clone ! Maps sequence length => count.
1 100000 [a,b) [
hailstone length ! Find sequence length.
over [ f>0 1 + ] change-at ! Add 1 to count.
] each
! Find the length-count pair with the highest count.
>alist unclip-slice [ max-value ] reduce
first2 swap
"Among Hailstone sequences from 1 <= n < 100000," print
"there are " write pprint
" sequences of length " write pprint "." print ;
PRIVATE>
MAIN: main

View file

@ -0,0 +1,11 @@
hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0
9!:29]1
9!:27'main 0'
main=:3 :0
smoutput 'Hailstone sequence for the number 27'
smoutput hailseq 27
smoutput ''
smoutput 'Finding number with longest hailstone sequence which is'
smoutput 'less than 100000 (and finding that sequence length):'
smoutput (I.@(= >./),>./) #@hailseq i.1e5
)

View file

@ -0,0 +1,6 @@
load jpath '~temp/hailseq.ijs'
Hailstone sequence for the number 27
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 ...
Finding number with longest hailstone sequence which is
less than 100000 (and finding that sequence length):
77031 351

View file

@ -0,0 +1,8 @@
require '~temp/hailseq.ijs'
9!:29]1
9!:27'main 0'
main=:3 :0
smoutput 'Finding most frequent hailstone sequence length for'
smoutput 'Hailstone sequences for whole numbers less than 100000:'
smoutput {:{.\:~ (#/.~,.~.) #@hailseq }.i.1e5
)

View file

@ -0,0 +1,4 @@
load jpath '~temp/66.ijs'
Finding most frequent hailstone sequence length for
Hailstone sequences for whole numbers less than 100000
72