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