I accidentally found this black hole question in the blog Park, which is suitable for Haskell practice. I tried to implement it with Haskell.
Original question description:
Sort the four numbers in a four-digit manner into a new number and a new number in a large to small arrangement. Then, the two numbers are subtracted and repeat this step, as long as the four digits in four digits are not repeated, the number will eventually become 6174.
For example:
32.16,9171 (= 9310-0139), 8532 (= 9711-1179), 6174 (= 8532-2358), 6174 ......
Import data. Charimport data . Listnextint 0 = 6174 -- when the four numbers are the same, 0 is returned Program There is an infinite sequence, so let the next number of 0 be 6174 Nextint x = Maxint-MININT where list = Sort (Inttodigits x) -- this sort is from small to large.Maxint = (Intfromdigits. Reverse) List MININT = Intfromdigits list
-- Converts the list of four numbers to an integer, for example, intfromdigits [1234,] = intfromdigits [d1 , D2, D3, D4] = D1 * 1000 + D2 * 100 + D3 * 10 + D4 -- split an integer into four integers, which can be 0. Example: inttodigits 1234 = [,]
Inttodigits x = R1 : D2: D3: D4 : [] -- Here we use a pattern to match 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
-- Generate the kaprekar sequence. (iterate nextint X) an infinite sequence is generated, and the number following 6174 is truncated with takewhile.
Kaprekar x= (Takewhile (/= 6174) (iterate nextint X) ++ [6174]
-- Try all the four digits from 1 to 9999, and only get the result with the length of 8.
Run= [Xs | Xs <-(MAP kaprekar [1 .. 9999]), (length XS) = 8]
The first 10 results are:
[[,],
[15,5085, 7992,7173, 6354,3087, 8352,6174],
[16,6084, 8172,7443, 3996,6264, 1166,6174],
[,],
[,],
[49,9351, 8172,7443, 3996,6264, 6,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]