icyrock.com

Home

PureScript solution to Project Euler problem 40

2021-Jan-31 14:34
purescriptproject-euler

Problem details at Project Euler problem 40 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module Euler040Test (euler40suite) where
 
import Prelude
 
import Data.Array (length)
import Euler040 (euler40)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler40suite :: TestSuite
euler40suite =
  suite "Euler 40" do
    test "Real" do
      pure unit -- Do not evaluate the below if not active
      Assert.equal 210 (euler40 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
module Euler040 where
 
import Prelude
 
import Data.Array (drop, head, snoc)
import Data.Foldable (product)
import Data.Maybe (Maybe(..))
 
digits :: Int -> Array Int
digits 0 = []
digits j = digits (j `div` 10) `snoc` (j `mod` 10)
 
digith :: Array Int -> Int -> Int -> Int -> Int
digith ds i c w =
  case head ds of
    Nothing -> digith (digits i) (i + 1) c w
    Just -> if c == w then d else digith (drop 1 ds) i (c + 1) w
 
digit :: Int -> Int
digit = digith [] 1 1
 
euler40 :: Unit -> Int
euler40 _ = (product <<< map digit) [1, 10, 100, 1000, 10000, 100000, 1000000]