Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,35 @@
import Data.List (transpose)
import System.Environment (getArgs)
import Text.Printf (printf)
-- Pascal's triangle.
pascal :: [[Int]]
pascal = iterate (\row -> 1 : zipWith (+) row (tail row) ++ [1]) [1]
-- The n by n Pascal lower triangular matrix.
pascLow :: Int -> [[Int]]
pascLow n = zipWith (\row i -> row ++ replicate (n-i) 0) (take n pascal) [1..]
-- The n by n Pascal upper triangular matrix.
pascUp :: Int -> [[Int]]
pascUp = transpose . pascLow
-- The n by n Pascal symmetric matrix.
pascSym :: Int -> [[Int]]
pascSym n = take n . map (take n) . transpose $ pascal
-- Format and print a matrix.
printMat :: String -> [[Int]] -> IO ()
printMat title mat = do
putStrLn $ title ++ "\n"
mapM_ (putStrLn . concatMap (printf " %2d")) mat
putStrLn "\n"
main :: IO ()
main = do
ns <- fmap (map read) getArgs
case ns of
[n] -> do printMat "Lower triangular" $ pascLow n
printMat "Upper triangular" $ pascUp n
printMat "Symmetric" $ pascSym n
_ -> error "Usage: pascmat <number>"

View file

@ -0,0 +1,45 @@
import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.Ix (range)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)
---------------------- PASCAL MATRIX ---------------------
pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [Int]
pascalMatrix f n =
bc . f
<$> range
((0, 0), join bimap pred (n, n))
-- Binomial coefficient
bc :: (Int, Int) -> Int
bc (n, k) =
foldr
(\x a -> quot (a * succ (n - x)) x)
1
[k, pred k .. 1]
--------------------------- TEST -------------------------
matrixSize = 5 :: Int
main :: IO ()
main =
mapM_
putStrLn
( unlines
. ( \(s, xs) ->
s :
(show <$> chunksOf matrixSize xs)
)
<$> zip
["Lower", "Upper", "Symmetric"]
( pascalMatrix
<$> [ id, -- Lower
swap, -- Upper
\(a, b) -> (a + b, b) -- Symmetric
]
<*> [matrixSize]
)
)