icyrock.com

Home

PureScript solution to Project Euler problem 22

2019-Jul-25 23:06
purescriptproject-euler

Problem details at Project Euler problem 22 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module Euler022Test (euler22suite) where
 
import Prelude
 
import Data.Maybe (Maybe(..))
import Effect.Class (liftEffect)
import Euler022 (euler22)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler22suite :: TestSuite
euler22suite =
  suite "Euler 22" do
    test "Warmup" do
      v <- liftEffect $ euler22 "warmup"
      Assert.equal 385 v
    test "Real" do
      v <- liftEffect $ euler22 "real"
      Assert.equal 871198282 v

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 Euler022 where
 
import Prelude
 
import Data.Array (length, range, sort, (!!))
import Data.Char (toCharCode)
import Data.Foldable (sum)
import Data.Maybe (maybe)
import Data.String (Pattern(..), Replacement(..), replaceAll, split)
import Data.String.CodeUnits (toCharArray)
import Effect (Effect)
import Node.Encoding (Encoding(..))
import Node.FS.Sync (readTextFile)
 
score :: Array String -> Int -> Int
score ls n =
  let cval c = toCharCode c - 64
      val = sum <<< map cval <<< toCharArray
  in (n + 1) * maybe 0 val (ls !! n)
 
scores :: String -> Int
scores s =
  let sr = replaceAll (Pattern "\"") (Replacement "") s
      ls = sort $ split (Pattern ",") sr
      ss = map (score ls) (range 0 (length ls - 1))
  in sum ss
 
euler22 :: String -> Effect Int
euler22 s = do
  t <- readTextFile UTF8 ("etc/022-names-" <> s <> ".txt")
  pure $ scores t