Archive for December, 2011

Programming Praxis – McNugget Numbers

December 9, 2011

In today’s Programming Praxis exercise, our goal is to determine all the numbers that are not McNugget numbers, i.e. numbers that cannot be created by summing multiples of 6, 9 and 20. Let’s get started, shall we?

A quick import:

import Data.List

The code is pretty straightforward: just take all the numbers up to 180 that cannot be created by a linear combination of 6, 9 and 20.

notMcNuggets :: [Integer]
notMcNuggets = [1..180] \\
    [a+b+c | a <- [0,6..180], b <- [0,9..180-a], c <- [0,20..180-a-b]]

To test whether everything works correctly:

main :: IO ()
main = print notMcNuggets

Yup. Nice and simple.

Advertisements

Programming Praxis – Pascal’s Triangle

December 6, 2011

In today’s Programming Praxis our task is to neatly display Pascal’s triangle. Let’s get started, shall we?

A quick import to making printing slightly more convenient:

import Text.Printf

Calculating Pascal’s triangle is trivial:

pascal :: [[Integer]]
pascal = iterate (\prev -> 1 : zipWith (+) prev (tail prev) ++ [1]) [1]

To display the triangle correctly, we need to prepend the appropriate amount of spacing to each line based on the longest (i.e. last) line.

prettyPascal :: Int -> IO ()
prettyPascal n = mapM_ (\r -> printf "%*s\n" (div (longest + length r) 2) r) rows
    where rows = map (unwords . map show) $ take (n + 1) pascal
          longest = length $ last rows

An that’s all there is to it. A quick test to see if everything is working proprely:

main :: IO ()
main = prettyPascal 10