Posts Tagged ‘characters’

Programming Praxis – Longest Substring Of Two Unique Characters

June 11, 2013

In today’s Programming Praxis exercise, our goal is to find the longest substring consisting of only two characters in a string. Let’s get started, shall we?

import Data.List

First, we group identical characters together and then take all the tails so that each tail starts with two unique groups of characters. This is to eliminate the need for special logic for cases where a substring starts with two identical characters. For each tail, we discard everything starting from the third unique letter. Of the remaining groups, we look for the longest one, giving preference to ones on the right.

lstuc :: Eq a => [a] -> [a]
lstuc xs = foldr (\x a -> if length x > length a then x else a) []
           [concat $ a:b:takeWhile (flip elem [head a, head b] . head) cs
           | (a:b:cs) <- tails $ group xs]

Some tests to see if everything is working properly:

main :: IO ()
main = do print $ lstuc "abcabcabcbcbc" == "bcbcbc"
          print $ lstuc "abababcabc"    == "ababab"
          print $ lstuc "abcacacabc"    == "cacaca"
          print $ lstuc "acacbdbd"      == "bdbd"
          print $ lstuc "aaccbdb"       == "aacc"
          print $ lstuc ""              == ""

Programming Praxis – Remove characters from a string

February 24, 2012

In today’s Programming Praxis exercise, our task is to remove all the characters in one string from the other. Let’s get started, shall we?

Since this exercise doesn’t mention any performance requirements, we’ll go with the short but naive version, which is O(m * n). If the strings used get larger, you’ll probably want to use different datastructures to have more efficient membership testing, such as a hastable which reduces the complexity to O(m).

remove :: Eq a => [a] -> [a] -> [a]
remove = filter . flip notElem

A quick test to see if it’s working properly:

main = print $ remove "aeiou" "Bonsai Code"