The past few days I have been solving problems at this site called Project Euler. This site contains many seemingly simple math programming problems. I have been using Haskell to solve the problems on the site and in order to help solve one of the problems I wrote this bit of code to generate palindromes.
palindrome :: (Integral a) => a -> [Char] -> [String] palindrome n al = concat $ map (pal n) al where pal :: (Integral a)=> a -> Char -> [String] pal n x | n > 2 = map (surround x) (palindrome (n-2) al) | n > 1 = [[x,x]] | otherwise = [[x]] where surround :: Char -> String -> String surround lt str = [lt] ++ str ++ [lt]
This code take a length(as an integer) and a list of characters and returns all possible palindromes that can be created. For example:
palindrome 3 [‘a’..’f’]
will result in
["aaa","aba","aca","ada","aea","afa","bab","bbb","bcb","bdb", "beb","bfb","cac","cbc","ccc","cdc","cec","cfc","dad","dbd", "dcd","ddd","ded","dfd","eae","ebe","ece","ede","eee", "efe","faf","fbf","fcf","fdf","fef","fff"]
While I doubt this is the greatest implementation of a method which generates palindromes, it was the first one I came up with and I am curious if anyone can do it in a very different (or better) way. So, if anyone reading this wants to show me a different way (in any language) feel free.