project-euler.044: more efficient algorithm
parent
13464d9403
commit
96ca914972
|
@ -1,7 +1,7 @@
|
||||||
! Copyright (c) 2008 Aaron Schaefer.
|
! Copyright (c) 2008 Aaron Schaefer.
|
||||||
! See http://factorcode.org/license.txt for BSD license.
|
! See http://factorcode.org/license.txt for BSD license.
|
||||||
USING: kernel math math.functions math.ranges math.order
|
USING: kernel math math.functions math.ranges math.order
|
||||||
project-euler.common sequences ;
|
project-euler.common sequences layouts ;
|
||||||
IN: project-euler.044
|
IN: project-euler.044
|
||||||
|
|
||||||
! http://projecteuler.net/index.php?section=problems&id=44
|
! http://projecteuler.net/index.php?section=problems&id=44
|
||||||
|
@ -29,20 +29,26 @@ IN: project-euler.044
|
||||||
<PRIVATE
|
<PRIVATE
|
||||||
|
|
||||||
: nth-pentagonal ( n -- seq )
|
: nth-pentagonal ( n -- seq )
|
||||||
dup 3 * 1 - * 2 / ;
|
dup 3 * 1 - * 2 /i ; inline
|
||||||
|
|
||||||
: sum-and-diff? ( m n -- ? )
|
: sum-and-diff? ( m n -- ? )
|
||||||
[ + ] [ - ] 2bi [ pentagonal? ] bi@ and ;
|
[ + ] [ - ] 2bi [ pentagonal? ] bi@ and ; inline
|
||||||
|
|
||||||
|
: euler044-step ( min m n -- min' )
|
||||||
|
[ nth-pentagonal ] bi@
|
||||||
|
2dup sum-and-diff? [ - abs min ] [ 2drop ] if ; inline
|
||||||
|
|
||||||
PRIVATE>
|
PRIVATE>
|
||||||
|
|
||||||
: euler044 ( -- answer )
|
: euler044 ( -- answer )
|
||||||
2500 [1,b] [ nth-pentagonal ] map dup cartesian-product
|
most-positive-fixnum >fixnum
|
||||||
[ first2 sum-and-diff? ] filter [ first2 - abs ] [ min ] map-reduce ;
|
2500 [1,b] [
|
||||||
|
2500 [1,b] [
|
||||||
|
euler044-step
|
||||||
|
] with each
|
||||||
|
] each ;
|
||||||
|
|
||||||
! [ euler044 ] 10 ave-time
|
! [ euler044 ] 10 ave-time
|
||||||
! 4996 ms ave run time - 87.46 SD (10 trials)
|
! 4996 ms ave run time - 87.46 SD (10 trials)
|
||||||
|
|
||||||
! TODO: this solution is ugly and not very efficient...find a better algorithm
|
|
||||||
|
|
||||||
SOLUTION: euler044
|
SOLUTION: euler044
|
||||||
|
|
|
@ -91,7 +91,7 @@ PRIVATE>
|
||||||
number>string natural-sort >string "123456789" = ;
|
number>string natural-sort >string "123456789" = ;
|
||||||
|
|
||||||
: pentagonal? ( n -- ? )
|
: pentagonal? ( n -- ? )
|
||||||
dup 0 > [ 24 * 1 + sqrt 1 + 6 / 1 mod zero? ] [ drop f ] if ;
|
dup 0 > [ 24 * 1 + sqrt 1 + 6 / 1 mod zero? ] [ drop f ] if ; inline
|
||||||
|
|
||||||
: penultimate ( seq -- elt )
|
: penultimate ( seq -- elt )
|
||||||
dup length 2 - swap nth ;
|
dup length 2 - swap nth ;
|
||||||
|
|
Loading…
Reference in New Issue