Haskell,140字节
在多次尝试失败后,我最终完成了此Haskell实现。我很高兴能成为APL解决方案的2分之一!
打高尔夫球的解决方案:
e=' ':e
m=[[]]:[[('/':e):map(' ':)x++('\\':e):y|k<-[0..n],x<-m!!(n-k),y<-m!!k]|n<-[0..]]
f n=putStr$unlines[map(!!(n-k))a|a<-m!!n,k<-[1..n]]
取消评论并评论:
该程序以递归方式构建n步山图集。每个图都由一列无限长的字符串表示,这些字符串表示横向绘制的山峰,其后延伸到无穷大的空间。这样可以确保所有图都具有相同的高度,这使得递归更加容易。山地打印机接受将高度限制为有限值的参数。
import Data.List (transpose)
-- Elementary picture slices, extending to infinity.
empty = ' ' : empty
up = '/' : empty
down = '\\': empty
-- A function which draws a mountain picture to stdout, clipping
-- its height to n.
printMtn n = putStr . unlines . reverse . take n . transpose
{-- Combine mountain pictures x and y by
x
x # y == / \y
--}
x # y = up : raised x ++ down : y
where raised = map (' ':)
-- Given two sets X,Y of mountain pictures, compute the set X <> Y of all
-- combined pictures x#y for x in X, y in Y.
xs <> ys = [ x # y | x <- xs, y <- ys ]
-- Compute the (++,<>)-convolution of a list with itself, e.g.:
-- autoConvolve [x0,x1,x2] == (x2 <> x0) ++ (x1 <> x1) ++ (x0 <> x2)
autoConvolve xs = concat $ zipWith (<>) (reverse xs) xs
{--
mtns is a list whose nth entry is the list of all n-step mountain diagrams.
It is defined recursively by:
-- The only 0-step mountain diagram is empty.
-- Each (n+1)-step diagram can be uniquely drawn as x#y for
some k-step diagram x and (n-k)-step diagram y.
--}
mtns = [[]] : [autoConvolve (prefix n) | n <- [1..]]
where prefix n = take n mtns
-- The driver function: apply the height n mountain printer to each
-- n-step mountain diagram. Whitespace is guaranteed by the order
-- in which the diagrams appear.
test n = mapM_ (printMtn n) $ mtns!!n
用法示例:
$ ghci mtn3.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( mtn3.hs, interpreted )
Ok, modules loaded: Main.
λ> f 3
/\
/ \
/ \
/\/\
/ \
/\
/ \/\
/\
/\/ \
/\/\/\
λ>