Home

PureScript solution to Project Euler problem 39

2020-Dec-04 07:39
purescriptproject-euler

Problem details at Project Euler problem 39 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module Euler039Test (euler39suite) where
 
import Prelude
 
import Data.Array (length)
import Data.Maybe (Maybe(..))
import Euler039 (euler39, rats)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler39suite :: TestSuite
euler39suite =
  suite "Euler 39" do
    test "Warmup" do
      Assert.equal 3 (length <<< rats $ 120)
    test "Real" do
      Assert.equal (Just 840) (euler39 1000)

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
module Euler039 where
 
import Prelude
 
import Control.MonadZero (guard)
import Data.Array (length, range)
import Data.Foldable (maximumBy)
import Data.Maybe (Maybe)
import Data.Tuple (Tuple(..), fst, snd)
 
ratp :: Int -> Int -> Int -> Boolean
ratp j k l = j * j + k * k == l * l
 
rats :: Int -> Array (Array Int)
rats p = do
  let p2 = p `div` 2
  j <- range 1 p2
  k <- range j p2
  let l = p - j - k
  guard $ k < l && ratp j k l
  pure [j, k, l]
 
euler39 :: Int -> Maybe Int
euler39 j =
  let f j = Tuple j (length <<< rats $ j)
      r = range 3 j
      m = map f r
  in fst <$> maximumBy (comparing snd) m