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:
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