icyrock.com

HomeOld blogOld blog 2

PureScript solution to Project Euler problem 56

2022-06-09 23:39

Problem details at Project Euler problem 56 page.

Test

module Euler056Test (euler56suite) where

import Prelude

import Euler056 (euler56, digitSum)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert

euler56suite :: TestSuite
euler56suite =
  suite "Euler 56" do
    test "Warmup" do
      Assert.equal 1 (digitSum 10 100)
      Assert.equal 1 (digitSum 100 100)

      Assert.equal 49 (digitSum 7 11)
      Assert.equal 145 (digitSum 19 23)

    test "Real" do
      Assert.equal 972 (euler56 unit)

Solution

module Euler056 where

import Prelude

import Data.Array (range)
import Data.BigInt as BI
import Data.Foldable (maximum, sum)
import Data.Int (fromString)
import Data.Maybe (fromJust)
import Data.String (singleton, toCodePointArray)
import Partial.Unsafe (unsafePartial)

digitSum :: Int -> Int -> Int
digitSum a b =
  let p = BI.pow (BI.fromInt a) (BI.fromInt b)
      dtoi = unsafePartial fromJust <<< fromString <<< singleton
      ds = (map dtoi <<< toCodePointArray <<< BI.toString) p
  in sum ds

euler56 :: Unit -> Int
euler56 _ = unsafePartial fromJust $ maximum do
  a <- range 1 99
  b <- range 1 99
  pure $ digitSum a b