You are viewing a single comment's thread. Return to all comments →
My solution in Haskell
I have a simpleTriangle function to build the base triangle for each level.
simpleTriangle
for example simpleTriangle 3 gives me :
simpleTriangle 3
___1___ __111__ _11111_ 1111111
I use this base 7×4 triangle to build the next Rank 8×15 triangle with the function buildNextRankTriangle like this :
buildNextRankTriangle
I build the top part 15×4 by adding "____" on both side
"____"
_______1_______ ______111______ _____11111_____ ____1111111____
I build the 15×4 bottom part with two 7×4 triangle with "_" between them
"_"
___1_______1___ __111_____111__ _11111___11111_ 1111111_1111111
I repeat this same process with the 15×4 to build the next rank. and so on.
size :: Int size = 6 main :: IO () main = do input <- getLine let n = read input :: Int mapM_ putStrLn (sierpinski n) main sierpinski :: Int -> [String] sierpinski n = iterate buildNextRankTriangle (simpleTriangle n) !! n buildNextRankTriangle :: [String] -> [String] buildNextRankTriangle triangle = buildTop triangle ++ buildBottom triangle buildTop :: [String] -> [String] buildTop triangle = [ side ++ s ++ side | s <- triangle] where side = replicate (length triangle) '_' buildBottom :: [String] -> [String] buildBottom triangle = [ s ++ "_" ++ s | s <- triangle] simpleTriangle :: Int -> [String] simpleTriangle n = map (generateLine n) [1..height] where height = 2 ^ (size - n) generateLine :: Int -> Int -> String generateLine rank n = replicate (width - n) '_' ++ replicate (2 * n - 1) '1' ++ replicate (width - n) '_' where width = 2 ^ (size - rank)
Functions and Fractals: Sierpinski triangles
You are viewing a single comment's thread. Return to all comments →
My solution in Haskell
I have a
simpleTriangle
function to build the base triangle for each level.for example
simpleTriangle 3
gives me :I use this base 7×4 triangle to build the next Rank 8×15 triangle with the function
buildNextRankTriangle
like this :I build the top part 15×4 by adding
"____"
on both sideI build the 15×4 bottom part with two 7×4 triangle with
"_"
between themI repeat this same process with the 15×4 to build the next rank. and so on.