|
发表于 2008-11-16 19:29:00
|
显示全部楼层
从表达上来讲, 楼主可能愿意把
for (i = 0; i <= 9; i++)
改为
for (i = '0'; i <= '9'; i++)
P.S. 最近在看 Haskell, 用 Haskell 写了一个, 提供四种解法, solve 看起来是穷举, 但是根据 haskell 的惰性求值原则, 实际上与 solve2 应该是一样的. solve2 则是手工根据各种不同的情况来进行处理. solve3 换了一种递归策略, solve4 进一步对 solve3 进行了归纳, 于是算法本身也描述得很清晰了. 由于本来也没打算让大家看明白, 因此注释就不加了, 纯当娱乐- main = do
- let (s, n) = ("1219", "1")
- --let (s, n) = ("172839", "3")
- --let (s, n) = ("312", "4")
- --let (s, n) = ("312", "1")
- --let (s, n) = ("555678", "3")
- --let (s, n) = ("555432", "3")
- --let (s, n) = ("555632", "3")
- --let (s, n) = ("555478", "3")
- --(s, n) <- input
- let result = solve s (read n)
- putStrLn ("result: " ++ result)
- let result2 = solve2 s (read n)
- putStrLn ("result2: " ++ result2)
- let result3 = solve3 s (read n)
- putStrLn ("result3: " ++ result3)
- let result4 = solve4 s (read n)
- putStrLn ("result4: " ++ result4)
- return ()
- input :: IO (String, String)
- input = do
- putStrLn "input S:"
- s <- getLine
- putStrLn "input N:"
- n <- getLine
- return (s, n)
- solve :: String -> Int -> String
- solve s 0 = s
- solve s n
- | (n >= length s) = ""
- solve (s0 : ss) n =
- min (s0 : solve ss n) (solve ss (n - 1))
- solve2 :: String -> Int -> String
- solve2 s 0 = s
- solve2 s n
- | (n >= length s) = ""
- solve2 (s0 : s1 : []) 1
- | (s0 < s1) = s0 : []
- | (s0 >= s1) = s1 : []
- solve2 (s0 : s1 : ss) 1
- | (s0 <= s1) = s0 : solve2 (s1 : ss) 1
- | (s0 > s1) = s1 : ss
- solve2 (s0 : s1 : ss) n
- | (s0 < s1) = s0 : solve2 (s1 : ss) n
- | (s0 > s1) = solve2 (s1 : ss) (n - 1)
- | (s0 == s1) = solve2 (s0 : solve2 (s1 : ss) (n - 1)) 1
- solve3 :: String -> Int -> String
- solve3 s 0 = s
- solve3 (s0 : s1 : []) 1
- | (s0 < s1) = s0 : []
- | (s0 >= s1) = s1 : []
- solve3 (s0 : s1 : ss) 1
- | (s0 <= s1) = s0 : solve3 (s1 : ss) 1
- | (s0 > s1) = s1 : ss
- solve3 s n =
- solve3 (solve3 s (n - 1)) 1
-
- solve4 :: String -> Int -> String
- solve4 s 0 = s
- solve4 (s0 : []) 1 = []
- solve4 (s0 : s1 : ss) 1
- | (s0 <= s1) = s0 : solve4 (s1 : ss) 1
- | (s0 > s1) = s1 : ss
- solve4 s n = solve4 (solve4 s (n - 1)) 1
-
- -- vim: set ts=4 sts=4 sw=4 et ai :
复制代码 |
|