Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1633,6 +1633,29 @@
"records"
],
"difficulty": 4
},
{
"slug": "palindrome-products",
"name": "Palindrome Products",
"uuid": "3ef15a49-8f28-4a27-aa83-695db65177f9",
"practices": [
"tail-call-recursion"
],
"prerequisites": [
"recursion",
"tail-call-recursion",
"lists",
"records",
"result",
"pattern-matching",
"custom-types",
"comparison",
"maybe",
"set",
"array",
"strings"
],
"difficulty": 8
}
],
"foregone": [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Instructions Append

```exercism/note
Naive solutions may take a long time to pass the tests involving four digit factors, likely longer than the time limit allocated to the online test runner.
You may need to work on the exercise locally to profile your solution.
There are efficient solutions to this exercise, but they are challenging.
```
36 changes: 36 additions & 0 deletions exercises/practice/palindrome-products/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Instructions

Detect palindrome products in a given range.

A palindromic number is a number that remains the same when its digits are reversed.
For example, `121` is a palindromic number but `112` is not.

Given a range of numbers, find the largest and smallest palindromes which
are products of two numbers within that range.

Your solution should return the largest and smallest palindromes, along with the factors of each within the range.
If the largest or smallest palindrome has more than one pair of factors within the range, then return all the pairs.

## Example 1

Given the range `[1, 9]` (both inclusive)...

And given the list of all possible products within this range:
`[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 15, 21, 24, 27, 20, 28, 32, 36, 25, 30, 35, 40, 45, 42, 48, 54, 49, 56, 63, 64, 72, 81]`

The palindrome products are all single digit numbers (in this case):
`[1, 2, 3, 4, 5, 6, 7, 8, 9]`

The smallest palindrome product is `1`.
Its factors are `(1, 1)`.
The largest palindrome product is `9`.
Its factors are `(1, 9)` and `(3, 3)`.

## Example 2

Given the range `[10, 99]` (both inclusive)...

The smallest palindrome product is `121`.
Its factors are `(11, 11)`.
The largest palindrome product is `9009`.
Its factors are `(91, 99)`.
19 changes: 19 additions & 0 deletions exercises/practice/palindrome-products/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"jiegillet"
],
"files": {
"solution": [
"src/PalindromeProducts.elm"
],
"test": [
"tests/Tests.elm"
],
"example": [
".meta/src/PalindromeProducts.example.elm"
]
},
"blurb": "Detect palindrome products in a given range.",
"source": "Problem 4 at Project Euler",
"source_url": "https://projecteuler.net/problem=4"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
module PalindromeProducts exposing (largest, smallest)

import Array exposing (Array)
import Set


type alias PalindromeProduct =
{ value : Int
, factors : List ( Int, Int )
}


smallest : Int -> Int -> Result String (Maybe PalindromeProduct)
smallest min max =
if min > max then
Err "min must be <= max"

else
let
initQueue =
new (\( i, j ) -> i * j) (<=)
|> insert ( min, min )

traverse queue visited =
case pop queue of
Nothing ->
Ok Nothing

Just ( ( i, j ), product, poppedQueue ) ->
if isPalindrome product then
popUntilDifferent { value = product, factors = [ ( i, j ) ] } poppedQueue

else if j > max then
traverse poppedQueue visited

else
let
newVisited =
visited |> Set.insert ( i, j + 1 ) |> Set.insert ( i + 1, j + 1 )

newQueue =
[ ( i, j + 1 ), ( i + 1, j + 1 ) ] |> List.filter (\pair -> not (Set.member pair visited)) |> List.foldl insert poppedQueue
in
traverse newQueue newVisited
in
traverse initQueue Set.empty


largest : Int -> Int -> Result String (Maybe PalindromeProduct)
largest min max =
if min > max then
Err "min must be <= max"

else
let
initQueue =
new (\( i, j ) -> i * j) (>)
|> insert ( max, max )

traverse queue visited =
case pop queue of
Nothing ->
Ok Nothing

Just ( ( i, j ), product, poppedQueue ) ->
if isPalindrome product then
popUntilDifferent { value = product, factors = [ ( i, j ) ] } poppedQueue

else if i < min then
traverse poppedQueue visited

else
let
neighbors =
[ ( i - 1, j ), ( i - 1, j - 1 ) ]

newVisited =
List.foldl Set.insert visited neighbors

newQueue =
neighbors
|> List.filter (\pair -> not (Set.member pair visited))
|> List.foldl insert poppedQueue
in
traverse newQueue newVisited
in
traverse initQueue Set.empty


isPalindrome : Int -> Bool
isPalindrome n =
let
string =
String.fromInt n
in
string == String.reverse string


popUntilDifferent : PalindromeProduct -> PriorityQueue ( Int, Int ) -> Result String (Maybe PalindromeProduct)
popUntilDifferent product queue =
case pop queue of
Nothing ->
Ok (Just { product | factors = List.sort product.factors })

Just ( pair, value, newQueue ) ->
if value == product.value then
popUntilDifferent { product | factors = pair :: product.factors } newQueue

else
Ok (Just { product | factors = List.sort product.factors })



-- Priority Queue


type alias PriorityQueue a =
{ leq : Int -> Int -> Bool
, toPriority : a -> Int
, heap : Heap a
}


type alias Heap a =
Array ( a, Int )


new : (a -> Int) -> (Int -> Int -> Bool) -> PriorityQueue a
new toPriority leq =
PriorityQueue leq toPriority Array.empty


insert : a -> PriorityQueue a -> PriorityQueue a
insert a ({ leq, toPriority, heap } as queue) =
{ queue | heap = insertHeap leq a (toPriority a) heap }


insertHeap : (Int -> Int -> Bool) -> a -> Int -> Heap a -> Heap a
insertHeap leq a p heap =
bubbleUp leq (Array.length heap) (Array.push ( a, p ) heap)


bubbleUp : (Int -> Int -> Bool) -> Int -> Heap a -> Heap a
bubbleUp leq index heap =
let
parentIndex =
(index - 1) // 2
in
case ( Array.get index heap, Array.get parentIndex heap ) of
( Just ( newA, newP ), Just ( parentA, parentP ) ) ->
if index > 0 && leq newP parentP then
bubbleUp leq
parentIndex
(heap
|> Array.set index ( parentA, parentP )
|> Array.set parentIndex ( newA, newP )
)

else
heap

_ ->
heap


pop : PriorityQueue a -> Maybe ( a, Int, PriorityQueue a )
pop ({ leq, heap } as queue) =
case Array.get 0 heap of
Nothing ->
Nothing

Just ( aTop, pTop ) ->
let
newHeap =
case Array.get (Array.length heap - 1) heap of
Nothing ->
heap

Just ( a, p ) ->
heap
|> Array.set 0 ( a, p )
|> Array.slice 0 (Array.length heap - 1)
|> bubbleDown leq 0
in
Just ( aTop, pTop, { queue | heap = newHeap } )


bubbleDown : (Int -> Int -> Bool) -> Int -> Heap a -> Heap a
bubbleDown leq index heap =
let
leftIndex =
index * 2 + 1

rightIndex =
index * 2 + 2
in
case ( Array.get index heap, Array.get leftIndex heap, Array.get rightIndex heap ) of
( Just ( a, p ), Just ( leftA, leftP ), Nothing ) ->
if leq p leftP then
heap

else
heap |> Array.set index ( leftA, leftP ) |> Array.set leftIndex ( a, p )

( Just ( a, p ), Just ( leftA, leftP ), Just ( rightA, rightP ) ) ->
if leq p leftP && leq p rightP then
heap

else if leq leftP rightP then
bubbleDown leq leftIndex (heap |> Array.set index ( leftA, leftP ) |> Array.set leftIndex ( a, p ))

else
bubbleDown leq rightIndex (heap |> Array.set index ( rightA, rightP ) |> Array.set rightIndex ( a, p ))

_ ->
heap
49 changes: 49 additions & 0 deletions exercises/practice/palindrome-products/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[5cff78fe-cf02-459d-85c2-ce584679f887]
description = "find the smallest palindrome from single digit factors"

[0853f82c-5fc4-44ae-be38-fadb2cced92d]
description = "find the largest palindrome from single digit factors"

[66c3b496-bdec-4103-9129-3fcb5a9063e1]
description = "find the smallest palindrome from double digit factors"

[a10682ae-530a-4e56-b89d-69664feafe53]
description = "find the largest palindrome from double digit factors"

[cecb5a35-46d1-4666-9719-fa2c3af7499d]
description = "find the smallest palindrome from triple digit factors"

[edab43e1-c35f-4ea3-8c55-2f31dddd92e5]
description = "find the largest palindrome from triple digit factors"

[4f802b5a-9d74-4026-a70f-b53ff9234e4e]
description = "find the smallest palindrome from four digit factors"

[787525e0-a5f9-40f3-8cb2-23b52cf5d0be]
description = "find the largest palindrome from four digit factors"

[58fb1d63-fddb-4409-ab84-a7a8e58d9ea0]
description = "empty result for smallest if no palindrome in the range"

[9de9e9da-f1d9-49a5-8bfc-3d322efbdd02]
description = "empty result for largest if no palindrome in the range"

[12e73aac-d7ee-4877-b8aa-2aa3dcdb9f8a]
description = "error result for smallest if min is more than max"

[eeeb5bff-3f47-4b1e-892f-05829277bd74]
description = "error result for largest if min is more than max"

[16481711-26c4-42e0-9180-e2e4e8b29c23]
description = "smallest product does not use the smallest factor"
29 changes: 29 additions & 0 deletions exercises/practice/palindrome-products/elm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"type": "application",
"source-directories": [
"src"
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/core": "1.0.5",
"elm/json": "1.1.3",
"elm/parser": "1.1.0",
"elm/random": "1.0.0",
"elm/regex": "1.0.0",
"elm/time": "1.0.0",
"elm/html": "1.0.0"
},
"indirect": {}
},
"test-dependencies": {
"direct": {
"elm-explorations/test": "2.1.0",
"rtfeldman/elm-iso8601-date-strings": "1.1.4"
},
"indirect": {
"elm/bytes": "1.0.8",
"elm/virtual-dom": "1.0.3"
}
}
}
Loading