Print Diamond Pattern using Haskell
haskell, io, recursion
Solution
For `n==0`, `next n` describes the whole picture up to mirroring. This is not the case anymore for greater `n`. So, in a first step, we change the `next` function to output a symmetric picture:
mmap = map . map
next :: Int -> [[Int]]
next 0 = [[1],[0,2],[1]]
next n = sn ++ map (\a -> a ++ map (+2*3^n) a) nn ++ sn
where
nn = next (n - 1)
sn = mmap (+3^n) nn
Now, `next n` describes the positions of all stars. To print them, we first compute the relative distances.
diffs :: [Int] -> [Int]
diffs (x:xs) = x: diffs' x (xs)
where
diffs' x (y:ys) = y - x - 1 : diffs' y ys
diffs' _ [] = []
diffs [] = []
lpad :: Int -> [[Char]]
lpad = map (concatMap $ \n -> replicate n ' ' ++ "*") . map diffs . next'
Applied to one line, `diffs` returns the list of the number of spaces we need to put before each star and `lpad` generates the picture from that. Print it as before:
pretty :: Int -> IO ()
pretty n = putStrLn $ unlines $ lpad n
Problem
I need to write a Haskell program that will generate a diamond output recursively. Here is some sample output for given input input : 1 output : ``` * * * * ``` input : 2 output : ``` * * * * * * * * * * * * * * * * ``` input : 3 output : ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` I wrote following functions: ``` next 0 = [1,0,1] next n = map (+3^n) (next (n-1)) ++ next (n-1) ++ map (+3^n) (next (n-1)) lpad n = map (++"*") (zipWith ($) (map (take)(next (n-1))) ((repeat(repeat ' ')))) pretty n = putStrLn $ intercalate "\n" $ lpad n ``` which gives following outputs: pretty 1 ``` * * * ``` pretty 2 ``` * * * * * * * * * ``` Can anyone help me with the remaining halves? Thanks in advance.