RosettaCodeData/Task/Cut-a-rectangle/D/cut-a-rectangle.d

78 lines
1.7 KiB
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons;
2013-04-10 16:57:12 -07:00
enum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];
__gshared ubyte[] grid;
2013-04-11 11:14:19 -07:00
__gshared uint w, h, len;
2013-04-10 16:57:12 -07:00
__gshared ulong cnt;
2013-04-11 11:14:19 -07:00
__gshared uint[4] next;
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
void walk(in uint y, in uint x) nothrow @nogc {
2013-04-10 16:57:12 -07:00
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
2013-04-11 11:14:19 -07:00
immutable t = y * (w + 1) + x;
2013-04-10 16:57:12 -07:00
grid[t]++;
grid[len - t]++;
2015-02-20 00:35:01 -05:00
foreach (immutable i; staticIota!(0, 4))
2013-04-10 16:57:12 -07:00
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--;
grid[len - t]--;
}
2015-02-20 00:35:01 -05:00
ulong solve(in uint hh, in uint ww, in bool recur) nothrow @nogc {
2013-04-10 16:57:12 -07:00
h = (hh & 1) ? ww : hh;
w = (hh & 1) ? hh : ww;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
2013-04-11 11:14:19 -07:00
immutable cy = h / 2;
immutable cx = w / 2;
2013-04-10 16:57:12 -07:00
len = (h + 1) * (w + 1);
{
2013-04-11 11:14:19 -07:00
// grid.length = len; // Slower.
alias T = typeof(grid[0]);
auto ptr = cast(T*)alloca(len * T.sizeof);
2013-04-10 16:57:12 -07:00
if (ptr == null)
exit(1);
grid = ptr[0 .. len];
}
grid[] = 0;
len--;
2013-04-11 11:14:19 -07:00
next = [-1, -w - 1, 1, w + 1];
2013-04-10 16:57:12 -07:00
if (recur)
cnt = 0;
2013-04-11 11:14:19 -07:00
foreach (immutable x; cx + 1 .. w) {
immutable t = cy * (w + 1) + x;
2013-04-10 16:57:12 -07:00
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
void main() {
2013-04-11 11:14:19 -07:00
foreach (immutable uint y; 1 .. 11)
foreach (immutable uint x; 1 .. y + 1)
2013-04-10 16:57:12 -07:00
if (!(x & 1) || !(y & 1))
printf("%d x %d: %llu\n", y, x, solve(y, x, true));
}