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

### Like this:

Like Loading...

*Related*

Tags: bonsai, code, Haskell, kata, numbers, pandigital, praxis, programming

This entry was posted on October 30, 2012 at 10:31 pm and is filed under Programming Praxis. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

October 31, 2012 at 3:21 pm |

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” ?

October 31, 2012 at 5:26 pm |

@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.