[ create a new paste ] login | about

Link: http://codepad.org/Tk9FL7Xk    [ raw code | fork ]

D, pasted on Jul 21:
version(Tango)
    import tango.stdc.stdio;
else
    import std.stdio;

template Tuple(T...) { alias T Tuple; }
alias Tuple!(-1,-2,-2,-1,+1,+2,+2,+1) movex;
alias Tuple!(-2,-1,+1,+2,+2,+1,-1,-2) movey;

const uint SIDE = 5;
const uint SQR_SIDE = SIDE * SIDE;

uint[SQR_SIDE] circuit;
uint nsolutions;

void showCircuit() {
    putchar('\n');
    for (uint x; x < SIDE; x++) {
        for (uint y; y < SIDE; y++)
            if (SQR_SIDE < 100U)
                printf("%02d ", circuit[x * SIDE + y]);
            else
                printf("%03d ", circuit[x * SIDE + y]);
        putchar('\n');
    }
}

void solve(uint nb, uint x, uint y) {
    uint newx, newy;

    circuit[x * SIDE + y] = nb;
    if (nb == SQR_SIDE) {
        version(doshow) showCircuit();
        nsolutions++;
        circuit[x * SIDE + y] = 0;
        return;
    }

    foreach (uint i, sx; movex) {
        newx = x + sx;
        if (newx < SIDE) {
            newy = y + movey[i];
            if (newy < SIDE && !circuit[newx * SIDE + newy])
                solve(nb+1, newx, newy);
        }
    }

    circuit[x * SIDE + y] = 0;
}

void main() {
    printf("Search for side=%d\n", SIDE);
    for (uint x; x < SIDE; x++)
        for (uint y; y < SIDE; y++)
            solve(1U, x, y);
    fprintf(stderr, "\n%dx%d case, %d solutions.\n", SIDE, SIDE, nsolutions);
}


Create a new paste based on this one


Comments: