1 ! Copyright (c) 2008 Eric Mertens.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel math ranges sequences project-euler.common ;
6 ! https://projecteuler.net/problem=116
11 ! A row of five black square tiles is to have a number of its
12 ! tiles replaced with colored oblong tiles chosen from red
13 ! (length two), green (length three), or blue (length four).
15 ! If red tiles are chosen there are exactly seven ways this can
16 ! be done. If green tiles are chosen there are three ways. And
17 ! if blue tiles are chosen there are two ways.
19 ! Assuming that colors cannot be mixed there are 7 + 3 + 2 = 12
20 ! ways of replacing the black tiles in a row measuring five
23 ! How many different ways can the black tiles in a row measuring
24 ! fifty units in length be replaced if colors cannot be mixed
25 ! and at least one colored tile must be used?
31 ! This solution uses a simple dynamic programming approach using
32 ! the following recurence relation
34 ! ways(n,_) = 0 | n < 0
36 ! ways(n,i) = ways(n-i,i) + ways(n-1,i)
37 ! solution(n) = ways(n,1) - 1 + ways(n,2) - 1 + ways(n,3) - 1
41 : nth* ( n seq -- elt/0 )
42 [ length swap - 1 - ] keep ?nth 0 or ;
44 : next ( colortile seq -- )
45 [ nth* ] [ last + ] [ push ] tri ;
47 : ways ( length colortile -- permutations )
48 V{ 1 } clone [ [ next ] 2curry times ] keep last 1 - ;
50 : (euler116) ( length -- permutations )
51 3 [1..b] [ ways ] with map-sum ;
55 : euler116 ( -- answer )
58 ! [ euler116 ] 100 ave-time
59 ! 0 ms ave run time - 0.34 SD (100 trials)