Home

PureScript solution to Project Euler problem 38

2020-Nov-25 19:21
purescriptproject-euler

Problem details at Project Euler problem 38 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module Euler038Test (euler38suite) where
 
import Prelude
 
import Data.Maybe (Maybe(..))
import Euler038 (euler38)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler38suite :: TestSuite
euler38suite =
  suite "Euler 38" do
    test "Real" do
      pure unit -- Do not evaluate the below if not active
      Assert.equal (Just 932718654) (euler38 unit)

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
module Euler038 where
 
import Prelude
 
import Data.Array (concatMap, filter, foldl, length, range, snoc, sort)
import Data.Foldable (maximum)
import Data.Maybe (Maybe)
 
is09pand :: Array Int -> Boolean
is09pand ds = length ds == 9 && sort ds == [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
int2arr :: Int -> Array Int
int2arr j
  | j < 10    = [j]
  | otherwise = int2arr (j `div` 10) `snoc` (j `mod` 10)
 
cprod :: Int -> Int -> Array Int
cprod j k = concatMap (int2arr <<< (j * _)) (range 1 k)
 
cprods :: Int -> Array (Array Int)
cprods j = filter is09pand $ map (cprod j) (range 2 6)
 
arr2int :: Array Int -> Int
arr2int = foldl (\j k -> 10 * j + k) 0
 
euler38 :: Unit -> Maybe Int
euler38 _ = (maximum <<< map arr2int <<< concatMap cprods) (range 1 9999)