]> gitweb.factorcode.org Git - factor.git/commitdiff
Add project-euler.116
authorEric Mertens <emertens@galois.com>
Wed, 16 Apr 2008 07:04:05 +0000 (00:04 -0700)
committerEric Mertens <emertens@galois.com>
Wed, 16 Apr 2008 07:04:05 +0000 (00:04 -0700)
extra/project-euler/116/116.factor [new file with mode: 0644]

diff --git a/extra/project-euler/116/116.factor b/extra/project-euler/116/116.factor
new file mode 100644 (file)
index 0000000..d48cdf1
--- /dev/null
@@ -0,0 +1,55 @@
+! Copyright (c) 2008 Eric Mertens
+! See http://factorcode.org/license.txt for BSD license.
+USING: kernel math math.ranges sequences sequences.lib ;
+
+IN: project-euler.116
+
+! http://projecteuler.net/index.php?section=problems&id=116
+
+! DESCRIPTION
+! -----------
+
+! A row of five black square tiles is to have a number of its tiles replaced
+! with coloured oblong tiles chosen from red (length two), green (length
+! three), or blue (length four).
+
+! If red tiles are chosen there are exactly seven ways this can be done.
+! If green tiles are chosen there are three ways.
+! And if blue tiles are chosen there are two ways.
+
+! Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of
+! replacing the black tiles in a row measuring five units in length.
+
+! How many different ways can the black tiles in a row measuring fifty units in
+! length be replaced if colours cannot be mixed and at least one coloured tile
+! must be used?
+
+! SOLUTION
+! --------
+
+! This solution uses a simple dynamic programming approach using the
+! following recurence relation
+
+! ways(n,_) = 0   | n < 0
+! ways(0,_) = 1
+! ways(n,i) = ways(n-i,i) + ways(n-1,i)
+! solution(n) = ways(n,1) - 1 + ways(n,2) - 1 + ways(n,3) - 1
+
+<PRIVATE
+
+: nth* ( n seq -- elt/0 )
+    [ length swap - 1- ] keep ?nth 0 or ;
+
+: next ( colortile seq -- )
+     [ nth* ] [ peek + ] [ push ] tri ;
+
+: ways ( length colortile -- permutations )
+    V{ 1 } clone [ [ next ] 2curry times ] keep peek 1- ;
+
+PRIVATE>
+
+: (euler116) ( length -- permutations )
+    3 [1,b] [ ways ] with sigma ;
+
+: euler116 ( -- permutations )
+    50 (euler116) ;