Posts Tagged ‘games’

Programming Praxis – Two Word Games

October 9, 2012

In today’s Programming Praxis exercise, our goal is to find all the words in a dictionary that satisfy two different criteria. Let’s get started, shall we?

First we have to find the words that have the five vowels in ascending order. To do this we simply check if the vowels in the words are equal to the five vowels in order.

ascVowels :: String -> Bool
ascVowels = (== "aeiou") . filter (`elem` "aeiou")

The second game is to find all the six-letter words whose letters are ascending. All we need to check is check the length and whether the first letter of each pair of subsequent letters comes before the second one.

sixAsc :: Ord b => [b] -> Bool
sixAsc s = length s == 6 && and (zipWith (<) s $ tail s)

All that’s left to do is to load the dictionary and print the appropriate words:

main :: IO ()
main = do ws <- fmap lines $ readFile "354984si.ngl"
          mapM_ putStrLn $ filter ascVowels ws
          putStrLn "---"
          mapM_ putStrLn $ filter sixAsc ws

Programming Praxis – Two Factoring Games

February 18, 2011

In today’s Programming Praxis exercise, our goal is to implement two algorithms related to prime factors; one to calculate the home prime of a number and one to generate the Euclid-Mullin sequence. Let’s get started, shall we?

Some imports:

import Data.List
import Data.Numbers.Primes

To calculate the home prime we repeatedly concatenate the digits of the prime factors until the number is prime.

homePrime :: Integer -> Integer
homePrime = head . filter isPrime .
            iterate (read . concatMap show . primeFactors)

The Eulic-Mullin sequence can be written as a basic unfold.

euclidMullin :: [Integer]
euclidMullin = unfoldr (\p -> let a = head (primeFactors $ p + 1)
                              in  Just (a, p * a)) 1

Naturally, we need to test if we did everything correctly:

main :: IO ()
main = do print $ homePrime 99 == 71143
          print $ take 10 euclidMullin ==
                  [2,3,7,43,13,53,5,6221671,38709183810571,139]

Looks like everything is working properly.