Fibonacci word: Difference between revisions

Content added Content deleted
(added Factor)
(→‎{{header|Factor}}: drastically reduced memory usage and run time)
Line 1,186: Line 1,186:


=={{header|Factor}}==
=={{header|Factor}}==
It is not necessary to calculate each fibonacci word, since every fibonacci word less than 37 is contained in the 37th fibonacci word. In order to obtain the nth fibonacci word ( <= 37 ), we start with the 37th fibonacci word and take the subsequence from index 0 to the nth fibonacci number, as in the standard fibonacci sequence.
<lang factor>USING: assocs combinators formatting kernel math math.functions
<lang factor>USING: assocs combinators formatting kernel math math.functions
math.ranges math.statistics pair-rocket sequences ;
math.ranges math.statistics namespaces pair-rocket sequences ;
IN: rosetta-code.fibonacci-word
IN: rosetta-code.fibonacci-word

SYMBOL: 37th-fib-word

: fib ( n -- m )
{
1 => [ 1 ]
2 => [ 1 ]
[ [ 1 - fib ] [ 2 - fib ] bi + ]
} case ;


: fib-word ( n -- seq )
: fib-word ( n -- seq )
{
{
1 => [ { 1 } ]
1 => [ "1" ]
2 => [ { 0 } ]
2 => [ "0" ]
[ [ 1 - fib-word ] [ 2 - fib-word ] bi append ]
[ [ 1 - fib-word ] [ 2 - fib-word ] bi append ]
} case ;
} case ;

: nth-fib-word ( n -- seq )
dup 1 =
[ drop "1" ] [ 37th-fib-word get swap fib head ] if ;
: entropy ( seq -- entropy )
: entropy ( seq -- entropy )
Line 1,202: Line 1,216:
[ dup log 2 log / * ] map-sum
[ dup log 2 log / * ] map-sum
dup 0. = [ neg ] unless ;
dup 0. = [ neg ] unless ;

37 fib-word 37th-fib-word set
"N" "Length" "Entropy" "%2s %8s %10s\n" printf
"N" "Length" "Entropy" "%2s %8s %10s\n" printf
37 [1,b] [
37 [1,b] [
dup fib-word [ length ] [ entropy ] bi
dup nth-fib-word [ length ] [ entropy ] bi
"%2d %8d %.8f\n" printf
"%2d %8d %.8f\n" printf
] each</lang>
] each</lang>
{{out}}
{{out}}