Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
20
Task/Spiral-matrix/D/spiral-matrix-1.d
Normal file
20
Task/Spiral-matrix/D/spiral-matrix-1.d
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
void main() {
|
||||
import std.stdio;
|
||||
enum n = 5;
|
||||
int[n][n] M;
|
||||
int pos, side = n;
|
||||
|
||||
foreach (immutable i; 0 .. n / 2 + n % 2) {
|
||||
foreach (immutable j; 0 .. side)
|
||||
M[i][i + j] = pos++;
|
||||
foreach (immutable j; 1 .. side)
|
||||
M[i + j][n - 1 - i] = pos++;
|
||||
foreach_reverse (immutable j; 0 .. side - 1)
|
||||
M[n - 1 - i][i + j] = pos++;
|
||||
foreach_reverse (immutable j; 1 .. side - 1)
|
||||
M[i + j][i] = pos++;
|
||||
side -= 2;
|
||||
}
|
||||
|
||||
writefln("%(%(%2d %)\n%)", M);
|
||||
}
|
||||
52
Task/Spiral-matrix/D/spiral-matrix-2.d
Normal file
52
Task/Spiral-matrix/D/spiral-matrix-2.d
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import std.stdio;
|
||||
|
||||
/// 2D spiral generator
|
||||
const struct Spiral {
|
||||
int w, h;
|
||||
|
||||
int opApply(int delegate(ref int, ref int, ref int) dg) {
|
||||
int idx, x, y, xy, dx = 1, dy;
|
||||
int[] subLen = [w, h-1];
|
||||
|
||||
void turn() {
|
||||
auto t = -dy;
|
||||
dy = dx;
|
||||
dx = t;
|
||||
xy = 1 - xy;
|
||||
}
|
||||
|
||||
void forward(int d = 1) {
|
||||
x += d * dx;
|
||||
y += d * dy;
|
||||
idx += d;
|
||||
}
|
||||
|
||||
Bye:
|
||||
while (true) {
|
||||
if (subLen[xy] == 0)
|
||||
break;
|
||||
foreach (_; 0 .. subLen[xy]--)
|
||||
if (dg(idx, x, y))
|
||||
break Bye;
|
||||
else
|
||||
forward();
|
||||
forward(-1);
|
||||
turn();
|
||||
forward();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int[][] spiralMatrix(int w, int h) {
|
||||
auto m = new typeof(return)(h, w);
|
||||
foreach (value, x, y; Spiral(w, h))
|
||||
m[y][x] = value;
|
||||
return m;
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (r; spiralMatrix(9, 4))
|
||||
writefln("%(%2d %)", r);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue