Programming Praxis – Pandigital Numbers

In today’s Programming Praxis exercise, our goal is to find all possible combinations in which two 3-digit sum up to a 4-digit number, with the condition that no digit is repeated in the three numbers. Let’s get started, shall we?

A quick import:

import Data.List

We’re going for the simple though somewhat inefficient approach of simply taking all possible combinations and filtering on the conditions we have. Checking for repeated digits is done by checking whether the string representation is equal to the string representation minus duplicate characters. Again, there are certainly quicker methods but since the whole program runs in 0.2 seconds anyway I personally prefer the short and easy to understand version.

pandigital :: [(Int, Int, Int)]
pandigital = [(a, b, a+b) | a <- d3, b <- d3, b > a, a+b > 999, unique [a, b, a+b]]
    where d3 = filter (unique . return) [100..999]
          unique = (\x -> x == nub x) . (show =<<)

Finding the smallest triplet of numbers is a separate task, but it’s a trivial one because our function returns all of them in ascending order, so we can simply take the first element.

main :: IO ()
main = do print $ head pandigital == (246,789,1035)
          print pandigital

Tags: , , , , , , ,

2 Responses to “Programming Praxis – Pandigital Numbers”

  1. ardnew Says:

    if i understand this correctly- in the first list comprehension, you use the constraint “b > a”.

    because of that, is it still necessary to filter the “[a, b, a+b]” with “unique” ?

  2. Remco Niemeijer Says:

    @ardnew: Yes, because unique checks the digits. Take for example the case a = 100, b = 101. b may be more than a, but the digits are certainly not unique.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: