icyrock.com

Home

PureScript solutions to Project Euler - problem 4

2018-Jan-22 06:53
purescriptproject-euler

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module Euler004Test (euler4suite) where
 
import Prelude
 
import Data.Maybe (Maybe(..))
import Euler004 (euler4)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler4suite :: forall e. TestSuite e
euler4suite =
  suite "Euler 4" do
    test "Warmup" do
      Assert.equal (Just 9009) (euler4 2)
    test "Real" do
      Assert.equal (Just 906609) (euler4 3)

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
module Euler004 (euler4, isPalindrome) where
 
import Prelude
 
import Data.Array (filter, range, reverse)
import Data.Foldable (maximum)
import Data.Int (decimal, pow, toStringAs)
import Data.Maybe (Maybe)
import Data.String (fromCharArray, toCharArray)
 
isPalindrome :: Int -> Boolean
isPalindrome n =
  let s = toStringAs decimal n
      rs = toCharArray s
           # reverse
           # fromCharArray
  in s == rs
 
euler4 :: Int -> Maybe Int
euler4 n =
  let low = pow 10 (n - 1)
      high = 10 * low - 1
      nums = range low high
      prods = (*) <$> nums <*> nums
      palins = filter isPalindrome prods
  in maximum palins