factor/extra/project-euler/085/085.factor

62 lines
1.5 KiB
Factor
Raw Normal View History

2009-09-04 21:59:04 -04:00
! Copyright (c) 2009 Guillaume Nargeot.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors kernel math math.ranges project-euler.common
sequences locals ;
2009-09-04 21:59:04 -04:00
IN: project-euler.085
! http://projecteuler.net/index.php?section=problems&id=85
! DESCRIPTION
! -----------
! By counting carefully it can be seen that a rectangular grid measuring
! 3 by 2 contains eighteen rectangles.
! Although there exists no rectangular grid that contains exactly two million
! rectangles, find the area of the grid with the nearest solution.
! SOLUTION
! --------
2009-09-15 08:01:25 -04:00
! A grid measuring x by y contains x * (x + 1) * y * (x + 1) / 4 rectangles.
2009-09-04 21:59:04 -04:00
<PRIVATE
: distance ( m -- n )
2000000 - abs ; inline
2009-09-04 21:59:04 -04:00
: rectangles-count ( a b -- n )
2dup [ 1 + ] bi@ * * * 4 /i ; inline
2009-09-04 21:59:04 -04:00
:: each-unique-product ( ... a b quot: ( ... i j -- ... ) -- ... )
a b [a,b] [| i |
i b [a,b] [| j |
i j quot call
] each
] each ; inline
2009-09-04 21:59:04 -04:00
TUPLE: result { area read-only } { distance read-only } ;
2009-09-04 21:59:04 -04:00
C: <result> result
2009-09-04 21:59:04 -04:00
: min-by-distance ( seq seq -- seq )
[ [ distance>> ] bi@ < ] most ; inline
: compute-result ( i j -- pair )
[ * ] [ rectangles-count distance ] 2bi <result> ; inline
2009-09-04 21:59:04 -04:00
: area-of-nearest ( -- n )
T{ result f 0 2000000 } 1 2000
[ compute-result min-by-distance ] each-unique-product area>> ;
2009-09-04 21:59:04 -04:00
PRIVATE>
: euler085 ( -- answer )
area-of-nearest ;
! [ euler085 ] 100 ave-time
2009-09-15 08:01:25 -04:00
! 791 ms ave run time - 17.15 SD (100 trials)
2009-09-04 21:59:04 -04:00
SOLUTION: euler085