! Copyright (c) 2008 Aaron Schaefer.
! See http://factorcode.org/license.txt for BSD license.
-USING: arrays combinators.lib kernel math math.matrices math.ranges namespaces
- sequences ;
+USING: arrays kernel math math.ranges
+ namespaces project-euler.common sequences ;
IN: project-euler.039
! http://projecteuler.net/index.php?section=problems&id=39
! --------
! Algorithm adapted from http://mathworld.wolfram.com/PythagoreanTriple.html
+! Identical implementation as problem #75
! Basically, this makes an array of 1000 zeros, recursively creates primitive
! triples using the three transforms and then increments the array at index
p-count get length ;
: adjust-p-count ( n -- )
- max-p 1- over <range> p-count get
- [ [ 1+ ] change-nth ] curry each ;
-
-: transform ( triple matrix -- new-triple )
- [ 1array ] dip m. first ;
-
-: u-transform ( triple -- new-triple )
- { { 1 2 2 } { -2 -1 -2 } { 2 2 3 } } transform ;
-
-: a-transform ( triple -- new-triple )
- { { 1 2 2 } { 2 1 2 } { 2 2 3 } } transform ;
-
-: d-transform ( triple -- new-triple )
- { { -1 -2 -2 } { 2 1 2 } { 2 2 3 } } transform ;
+ max-p 1 - over <range> p-count get
+ [ [ 1 + ] change-nth ] curry each ;
: (count-perimeters) ( seq -- )
dup sum max-p < [
dup sum adjust-p-count
- [ u-transform ] keep [ a-transform ] keep d-transform
- [ (count-perimeters) ] 3apply
+ [ u-transform ] [ a-transform ] [ d-transform ] tri
+ [ (count-perimeters) ] tri@
] [
drop
] if ;
] with-scope ;
! [ euler039 ] 100 ave-time
-! 2 ms run / 0 ms GC ave time - 100 trials
+! 1 ms ave run time - 0.37 SD (100 trials)
-MAIN: euler039
+SOLUTION: euler039