我正在Euler项目上做problem 112,并提出以下内容来测试示例案例(我将answer
中的数字更改为0.99以获得真实答案):
isIncre x | x == 99 = False
| otherwise = isIncre' x
where
isIncre' x = ???
isDecre x = isIncre (read $ reverse $ show x :: Int)
isBouncy x = (isIncre x == False) && (isDecre x == False)
bouncers x = length [n|n<-[1..x],isBouncy n]
nonBouncers x = length [n|n<-[1..x],(isBouncy n) == False]
answer = head [x|x<-[1..],((bouncers x) / (nonBouncers x)) == 0.5]
但是我不知道该怎么做是定义一个函数
isIncre'
来测试数字中的数字是否大于或等于其左边的数字。我知道它需要递归进行,但是怎么做呢?附带一提,我知道我只能在两个浮点数上使用
/
,但是如何使bouncers
的输出成为浮点数而不是整数?编辑:
感谢您的帮助,但是当我将
=
更改为:时,它不喜欢isIncre
:isIncre x | x <= 99 = False
| otherwise = isIncre' (mshow x)
where
isIncre' (x:y:xs) = (x <= y) && (isIncre' (y:xs))
isIncre' _ = True
最佳答案
如果您使用整数表示字符串,则可以这样编写isIncre函数(ord将字符转换为整数,而字符串只是一个字符列表):
isIncre (x:y:xs) = ord x <= ord y && isIncre (y:xs)
isIncre _ = True
最好编写不带ord的isIncre函数,处理任何有序类型,然后在调用它时将其与“ map ord”结合使用。这样的实现就是:
isIncre (x:y:xs) = x <= y && isIncre (y:xs)
isIncre _ = True
如果x是整数,可以这样称呼
isIncre (map ord (show x))