1 ! Copyright (c) 2009 Guillaume Nargeot.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.ranges project-euler.common sequences ;
6 ! http://projecteuler.net/index.php?section=problems&id=85
11 ! By counting carefully it can be seen that a rectangular grid measuring
12 ! 3 by 2 contains eighteen rectangles.
14 ! Although there exists no rectangular grid that contains exactly two million
15 ! rectangles, find the area of the grid with the nearest solution.
21 ! A grid measuring x by y contains x * (x + 1) * y * (x + 1) rectangles.
28 : rectangles-count ( a b -- n )
29 2dup [ 1 + ] bi@ * * * 4 / ;
31 : unique-products ( a b -- seq )
33 over dupd [a,b] [ 2array ] with map
36 : max-by-last ( seq seq -- seq )
37 [ [ last ] bi@ < ] most ;
39 : array2 ( seq -- a b )
40 [ first ] [ last ] bi ;
42 : convert ( seq -- seq )
43 array2 [ * ] [ rectangles-count distance ] 2bi 2array ;
45 : area-of-nearest ( -- n )
46 1 2000 unique-products
47 [ convert ] [ max-by-last ] map-reduce first ;
51 : euler085 ( -- answer )
54 ! [ euler085 ] 100 ave-time
55 ! 2285 ms ave run time - 4.8 SD (100 trials)