Home

PureScript solution to Project Euler problem 52

2022-Jan-31 13:53
purescriptproject-euler

Problem details at Project Euler problem 52 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module Euler052Test (euler52suite) where
 
import Prelude
 
import Data.Maybe (Maybe(..))
import Euler052 (euler52)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler52suite :: TestSuite
euler52suite =
  suite "Euler 52" do
    test "Warmup" do
      Assert.equal (Just 125874) (euler52 2 200_000)
 
    test "Real" do
      Assert.equal (Just 142857) (euler52 6 200_000)

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
29
30
31
module Euler052 where
 
import Prelude
 
import Data.Array (fromFoldable, sort)
import Data.List as L
import Data.Maybe (Maybe(..))
 
digits :: Int -> Array Int
digits ni =
  let go n
        | n < 10    = L.singleton n
        | otherwise = n `mod` 10 L.: go (n `div` 10)
  in sort $ fromFoldable $ go ni
 
sameDigits :: Int -> Int -> Boolean
sameDigits di n =
  let ds = digits n
      go d
        | d > di               = true
        | digits (d * n) /= ds = false
        | otherwise            = go (d + 1)
  in go 2
 
euler52 :: Int -> Int -> Maybe Int
euler52 d m =
  let go j
        | j > m          = Nothing
        | sameDigits d j = Just j
        | otherwise      = go (j + 1)
  in go 1