这种顺时针的n*n矩阵.....这个不是最优解,仅供参考
- let
- Table.SpiralMatrix=(n)=>
- let
- //先生成一张n×n的空表格t,然后ToRecords,比如15×15
- t = Table.ToRecords(#table(List.Transform({0..n-1},Text.From),List.Repeat({List.Repeat({""},n)},n))),
-
- s = List.Accumulate( {0..Number.RoundDown((n-1)/2)}, //这个表示由外而内需要循环的圈数。
- {t,0}, //{源和变化后的records,每一圈循环的起始值在list{1..n*n}中的位置}
- (x,y)=>let i = (n-y)*4-(y+1)*4 //这个i表示每一圈循环的数的个数,比如第1圈56个数,第2圈48个数...
- in { List.Accumulate( List.Range({1..n*n},x{1},if i=0 then 1 else i), //每一圈循环的那些数取值
- {x{0},y,y}, //这里的y,y是指某行某列
- (s,c)=>let fld = Text.From(s{2}),
- rcd = Record.FromList({c},{fld}),
- lst = List.ReplaceRange(s{0},s{1},1,{s{0}{s{1}}&rcd})
- in if s{1}=y and s{2}=y then {lst,s{1},s{2}+1} else //循环起点
- if s{1}=y and s{2}<n-y-1 then {lst,s{1},s{2}+1} else //往右
- if s{1}<n-y-1 and s{2}=n-y-1 then {lst,s{1}+1,s{2}} else //往下
- if s{1}=n-y-1 and s{2}>y then {lst,s{1},s{2}-1} else //往左
- {lst,s{1}-1,s{2}}){0}, //往上
- x{1}+(n-y)*4-(y+1)*4 } //下一次循环取数的起点位置
- ),
- r = Table.FromRecords(s{0})
- in
- r,
- Output = Table.SpiralMatrix(15)
- in
- Output
复制代码
|