1 ! Copyright (c) 2010 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: generalizations kernel math math.functions project-euler.common
7 ! http://projecteuler.net/index.php?section=problems&id=265
9 ! 2^(N) binary digits can be placed in a circle so that all the N-digit
10 ! clockwise subsequences are distinct.
12 ! For N=3, two such circular arrangements are possible, ignoring rotations.
14 ! For the first arrangement, the 3-digit subsequences, in clockwise order, are:
15 ! 000, 001, 010, 101, 011, 111, 110 and 100.
17 ! Each circular arrangement can be encoded as a number by concatenating
18 ! the binary digits starting with the subsequence of all zeros as the most
19 ! significant bits and proceeding clockwise. The two arrangements for N=3 are
20 ! thus represented as 23 and 29:
24 ! Calling S(N) the sum of the unique numeric representations, we can see that S(3) = 23 + 29 = 52.
30 : decompose ( n -- seq )
31 N iota [ drop [ 2/ ] [ 1 bitand ] bi ] map nip reverse ;
34 0 [ [ 2 * ] [ + ] bi* ] reduce ;
36 : complete ( seq -- seq' )
37 unclip decompose append [ 1 bitand ] map ;
39 : rotate-bits ( seq -- seq' )
40 dup length iota [ cut prepend bits ] with map ;
42 : ?register ( acc seq -- )
44 dup [ 2 N ^ mod ] map all-unique? [ infimum swap push ] [ 2drop ] if ;
46 : add-bit ( seen bit -- seen' t/f )
47 over last 2 * + 2 N ^ mod
48 2dup swap member? [ drop f ] [ suffix t ] if ;
50 : iterate ( acc left seen -- )
55 { 0 1 } [ add-bit [ iterate ] [ 3drop ] if ] 3 nwith each
58 : euler265 ( -- answer )
59 V{ } clone [ 2 N ^ N - { 0 } iterate ] [ sum ] bi ;
62 ! Running time: 0.376389019 seconds