练习:在 n×n n × n 矩阵填充连续自然数,例如:
?????11211102131693141584567????? ( 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 )
今天我打算抱一颗平常心,不追求代码行最少,按照 C 语言的习惯,慢条斯理写出这个算法。放下心理包袱,感觉好极了。
snakeRect n = snakeRect_ n 0where snakeRect_ 0 k = []snakeRect_ 1 k = [[k+1]]snakeRect_ n k = [[k+1..k+n]] ++ mid ++ [reverse [k+2*n-1.. k+3*n-2]]whereleftSize = [[x]|x<-[k+4*n-4,k+4*n-5.. k+3*n-1]]rightSide = [[x]|x<-[k+n+1..k+2*n-2]]mid_ = zipWith (++) (snakeRect_ (n-2) (k+n*4-4)) rightSidemid = zipWith (++) leftSize mid_ //run it ...>> snakeRect 0
[]>> snakeRect 1
[[1]]>> snakeRect 2
[
[1,2],
[4,3]]>> snakeRect 3
[
[1,2,3],
[8,9,4],
[7,6,5]]>> snakeRect 4
[
[1, 2, 3, 4],
[12,13,14,5],
[11,16,15,6],
[10,9, 8, 7]]>> snakeRect 5
[
[ 1, 2, 3, 4, 5],
[16,17,18,19, 6],
[15,24,25,20, 7],
[14,23,22,21, 8],
[13,12,11,10, 9]]>> snakeRect 6
[
[ 1, 2, 3, 4, 5, 6],
[20,21,22,23,24, 7],
[19,32,33,34,25, 8],
[18,31,36,35,26, 9],
[17,30,29,28,27,10],
[16,15,14,13,12,11]]>> snakeRect 7
[
[ 1, 2, 3, 4, 5, 6, 7],
[24,25,26,27,28,29, 8],
[23,40,41,42,43,30, 9],
[22,39,48,49,44,31,10],
[21,38,47,46,45,32,11],
[20,37,36,35,34,33,12],
[19,18,17,16,15,14,13]]