3109，9171 (=9310 - 0139)，8532 (=9711 - 1179)，6174 (=8532 - 2358)，6174 ......

import Data.Char
import Data.List

nextInt 0 = 6174  -- 当4个数字相同时，会得到0的结果，会使程序出现一个无限序列，所以让0的下一个数为6174
nextInt x = maxInt - minInt
where list = sort (intToDigits x)  --这种排序是从小到大的
maxInt = (intFromDigits . reverse) list
minInt = intFromDigits list
-- 把4个数字的列表转换为整数，例如intFromDigits [1,2,3,4] = 1234
intFromDigits [d1,d2,d3,d4] = d1*1000 + d2*100 + d3*10 + d4

-- 把一个整数拆分成4个整数，可以有0。例如：intToDigits 1234 = [1,2,3,4]intToDigits x = r1:d2:d3:d4:[]   -- 这里用了一种模式匹配
where (r3,d4) =  x divMod 10  -- 1234 divMod 10 = (123, 4), r3=123,  d4=4
(r2,d3) = r3 divMod 10  -- 123 divMod 10 = (12, 3), r2=12,  d3=3          (r1,d2) = r2 divMod 10  -- 12 divMod 10 = (1, 2), r1=1,  d2=2
-- 生成kaprekar序列, (iterate nextInt x)会生成一个无穷序列，前面用takeWhile把6174后面的数都截断掉kaprekar x = (takeWhile (/=6174) (iterate nextInt x)) ++ [6174]-- 把1到9999的所有4位数都试一遍，只取长度为8的结果run = [xs | xs<-(map kaprekar [1..9999]), (length xs)==8]

前10个结果是：

[[14,4086,8172,7443,3996,6264,4176,6174],

[15,5085,7992,7173,6354,3087,8352,6174],

[16,6084,8172,7443,3996,6264,4176,6174],

[25,5175,5994,5355,1998,8082,8532,6174],

[41,4086,8172,7443,3996,6264,4176,6174],

[49,9351,8172,7443,3996,6264,4176,6174],

[51,5085,7992,7173,6354,3087,8352,6174],

[52,5175,5994,5355,1998,8082,8532,6174],

[58,8442,5994,5355,1998,8082,8532,6174],

[59,9441,7992,7173,6354,3087,8352,6174]]

posted @ 2013-02-06 22:57  申龙斌的程序人生  阅读(1527)  评论(2编辑  收藏  举报