]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/265/265.factor
f9ae9393fcfb80dc54ec3b6bed25fd354a439610
[factor.git] / extra / project-euler / 265 / 265.factor
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 ;
4 IN: project-euler.265
5
6 ! http://projecteuler.net/index.php?section=problems&id=265
7
8 ! 2^(N) binary digits can be placed in a circle so that all the N-digit
9 ! clockwise subsequences are distinct.
10
11 ! For N=3, two such circular arrangements are possible, ignoring rotations.
12
13 ! For the first arrangement, the 3-digit subsequences, in clockwise order, are:
14 ! 000, 001, 010, 101, 011, 111, 110 and 100.
15
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:
20 ! 00010111 _(2) = 23
21 ! 00011101 _(2) = 29
22
23 ! Calling S(N) the sum of the unique numeric representations, we can see that S(3) = 23 + 29 = 52.
24
25 ! Find S(5).
26
27 CONSTANT: N 5
28
29 : decompose ( n -- seq )
30     N iota [ drop [ 2/ ] [ 1 bitand ] bi ] map nip reverse ;
31
32 : bits ( seq -- n )
33     0 [ [ 2 * ] [ + ] bi* ] reduce ;
34
35 : complete ( seq -- seq' )
36     unclip decompose append [ 1 bitand ] map ;
37
38 : rotate-bits ( seq -- seq' )
39     dup length iota [ cut prepend bits ] with map ;
40
41 : ?register ( acc seq -- )
42     complete rotate-bits
43     dup [ 2 N ^ mod ] map all-unique? [ infimum swap push ] [ 2drop ] if ;
44
45 : add-bit ( seen bit -- seen' t/f )
46     over last 2 * + 2 N ^ mod
47     2dup swap member? [ drop f ] [ suffix t ] if ;
48
49 : iterate ( acc left seen -- )
50     over 0 = [
51         nip ?register
52     ] [
53         [ 1 - ] dip
54         { 0 1 } [ add-bit [ iterate ] [ 3drop ] if ] with with with each
55     ] if ;
56
57 : euler265 ( -- answer )
58     V{ } clone [ 2 N ^ N - { 0 } iterate ] [ sum ] bi ;
59
60 ! [ euler265 ] time
61 ! Running time: 0.376389019 seconds
62
63 SOLUTION: euler265