Knight's Challenge in D

bearophile bearophileHUGS at lycos.com
Wed Apr 2 03:08:27 PDT 2008


To help you improve your D skills here are few notes on the first D program (the solver):
- I suggest you to put as many globals inside functions/structs as possible, to reduce global namespace pollution, so 'access' can go in loc (Loc) and vectors in 'get_legal_moves'.
- to improve readability you can put a space around operators, like in isLegalLocation.
- you may want to use a global const N = 8 instead of putting 8 everywhere.
- print_solution() shows why Python syntax is better, you can replace the first long ugly line with something like:
print "  ".join("%2d" % el for el in row)
You can do something similar with a functional lib, but it gets a bit too much hairy:
putr( map((int el){ return format("%2d", el);}, row).join("  ") );
- generally try to use less for() and more foreach, so 'clear_board' can contain just:
foreach (ref row; board)
    row[] = -1;
- opCmp can be simplified, removing the other struct method.
- Some time is spent sorting, so using a faster sort (like my fastSort) you can reduce running time. The running time for this first program goes from 0.85 s to 0.53 s on my old PC.
- In the attach there is the version with those changes (for Phobos!).

The code of your SVGmaker isn't nice looking at all (and it doesn't show the point of the arrow), the Perl version is much more readable and short (despite Perl being generally not much readable). Probably Perl is better for that kind of code, so you may want to keep it in Perl (and use D for the generation of solutions. Sometimes two languages are better than one). In alternative you can avoid most of the the parsing, creating a second printing function in the first program like this:

void print_moves(int start_loc_x, int start_loc_y) {
    char[2 * N * N] moves;
    foreach(r, row; board)
        foreach(c, el; row) {
            moves[el * 2] = '0' + r;
            moves[el * 2 + 1] = '0' + c;
        }
    writefln(moves);
}


>I was using Java, and back then with only version 1.4.2 it didn't get very far, or very fast, either.<

What's the running time of a Java version?

Bye,
bearophile
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Miller.d
Type: application/octet-stream
Size: 2946 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20080402/e0e5aab7/attachment.obj>


More information about the Digitalmars-d mailing list