How to solve this problem using FP?
时间:2013-09-24
来源:互联网
http://www.spoj.com/problems/ULM02/
I have no ideas how to solve it using functional paradigm.
Can anyone give me some advice? Thanks.
[ 本帖最后由 fitcat07 於 2013-8-30 11:20 AM 编辑 ]
作者: fitcat07 发布时间: 2013-09-24
Int -> [String]
i.e. It turn a number into a list of string representing the output. Use recursion to construct larger output from smaller one. You most likely need some auxiliary functions to pad spaces on the left and right.
作者: code4food 发布时间: 2013-09-24
First draw the biggest one and then recursively draw the smaller ones.
This is why I was stuck when thinking in FP.

How to draw it reversely? I need some time to think about it.
Thanks for the reply.

作者: fitcat07 发布时间: 2013-09-25
sierpinski :: Int -> [String]
sierpinski n
| n == 1 = [" /\\",
"/__\\"]
| n > 1 = let sub = sierpinski $ n - 1
h = 2 ^ (n-1)
top_pad = replicate h ' '
top = map (top_pad ++) sub
bot_pad = map (\l -> replicate l ' ') [h-1,h-2..0]
bot = zipWith (\x y -> x ++ y ++ x) sub bot_pad
in top ++ bot
| otherwise = error "n must be positive"
main :: IO ()
main = do n <- liftM read getLine
if n /= 0
then do forM_ (sierpinski n) putStrLn
main
else return ()
[ 本帖最后由 code4food 於 2013-8-31 10:26 PM 编辑 ]
作者: code4food 发布时间: 2013-09-25

Glad for learning something new.

Thanks for sharing.

作者: fitcat07 发布时间: 2013-09-25
Haskell is amazing.

作者: fitcat07 发布时间: 2013-09-25
Your solution got AC!
Haskell is amazing.


不过我用部MacBookPro试,做1-10加埋都系0.7秒。可能系lazy evaluation嘅关系。
作者: code4food 发布时间: 2013-09-25
sierpinski n i j = .....
作者: code4food 发布时间: 2013-09-25
o下,啖都得?

不过我用部MacBookPro试,做1-10加埋都系0.7秒。可能系lazy evaluation嘅关系。
不过,暂时 tail recursion removal 好似唔系 Haskell 嘅 compiler's requirement...
作者: fitcat07 发布时间: 2013-09-25
For fun, you can also solve this problem using another approach. You can compute the character at row i, column j of a Sierpinski fractal with recursion depth n.
sierpinski :: Int -> Int -> Int -> ...
作者: fitcat07 发布时间: 2013-09-25
My C++ solution works in this way. So, I initially considered the FP solution in this way but I was stuck...
作者: code4food 发布时间: 2013-09-25
作者: code4food 发布时间: 2013-09-25
作者: ricyik 发布时间: 2013-09-25
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28