Personal tools

Haskell Quiz/PP Pascal/Solution Kelan

From HaskellWiki

< Haskell Quiz | PP Pascal(Difference between revisions)
Jump to: navigation, search
(Added my solution)
 
m
 
(One intermediate revision by one user not shown)
Line 1: Line 1:
  +
[[Category:Haskell Quiz solutions|PP Pascal]]
 
Pretty basic solution. Find the biggest number the triangle will contain given the number of rows, use that number to determine column widths. Then just print out each row with the correct columns and spacing.
 
Pretty basic solution. Find the biggest number the triangle will contain given the number of rows, use that number to determine column widths. Then just print out each row with the correct columns and spacing.
   
 
<haskell>
 
<haskell>
 
import System.Environment
 
import System.Environment
  +
import Control.Monad (forM_)
   
 
nCr n r =
 
nCr n r =
Line 21: Line 23:
 
digits = 1 + ( truncate . logBase 10 . fromIntegral . trimax $ rows )
 
digits = 1 + ( truncate . logBase 10 . fromIntegral . trimax $ rows )
 
pad s = ( replicate ( digits - length s ) ' ' ) ++ s
 
pad s = ( replicate ( digits - length s ) ' ' ) ++ s
for_ = flip mapM_
 
   
for_ [ 0 .. ( rows - 1 ) ] $ \ n -> do
+
forM_ [ 0 .. ( rows - 1 ) ] $ \ n -> do
 
putStr . concat . replicate ( rows - n - 1 ) . pad $ ""
 
putStr . concat . replicate ( rows - n - 1 ) . pad $ ""
for_ [ 0 .. n ] $ \ r -> do
+
forM_ [ 0 .. n ] $ \ r -> do
 
putStr . pad . show . nCr n $ r
 
putStr . pad . show . nCr n $ r
 
putStr . pad $ ""
 
putStr . pad $ ""

Latest revision as of 21:15, 14 December 2009

Pretty basic solution. Find the biggest number the triangle will contain given the number of rows, use that number to determine column widths. Then just print out each row with the correct columns and spacing.

import System.Environment
import Control.Monad (forM_)
 
nCr n r =
    ( product [ ( s + 1 ) .. n ] ) `div` ( product [ 2 .. t ] )
    where
    s = max r ( n - r )
    t = min r ( n - r )
 
-- maximum number in a pascal triangle
-- with given number of rows
trimax rows =
    nCr ( rows - 1 ) ( ( rows - 1 ) `div` 2 )
 
main = do
    args <- getArgs
 
    let rows = read . head $ args
        digits = 1 + ( truncate . logBase 10 . fromIntegral . trimax $ rows )
        pad s = ( replicate ( digits - length s ) ' ' ) ++ s
 
    forM_ [ 0 .. ( rows - 1 ) ] $ \ n -> do
        putStr . concat . replicate ( rows - n - 1 ) . pad $ ""
        forM_ [ 0 .. n ] $ \ r -> do
            putStr . pad . show . nCr n $ r
            putStr . pad $ ""
        putStrLn ""