Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Lisp and Scheme have helped my C programming

Name: Anonymous 2008-04-23 22:58

Yesterday I wrote a silly program that randomly places queens onto a chess board until every space either has a queen or is blocked by a queen. The "hardest" part was writing the code to mark the appropriate spaces as blocked by the placement of a new queen.

I started by writing code like this.

if(r >= 0)
    for(i = r - NUM_COLS; i >= 0; i -= NUM_COLS)
        mark(board, i, BLOCK);


But after doing this for the first couple types of blocks, I realized that I could factor a pattern out of it.


if(blocks[j].pre(r, r) == blocks[j].expected_pre)
    for(i = r + blocks[j].change;
        blocks[j].during(i, r) == blocks[j].expected_during;
        i += blocks[j].change)
            mark(board, i, BLOCK);


Then I could just write an array of structures that hold information on the prerequisites for each type of block, the loop checking function, and the loop change offset, like this.


Block blocks[] = {
    {isUnderTopEdge,    true,  isUnderTopEdge,    true,  -NUM_COLS},
    {isAboveBottomEdge, true,  isAboveBottomEdge, true,  NUM_COLS},
    {isLeftEdge,        false, isRightEdge,       false, -1},
    {isRightEdge,       false, isLeftEdge,        false, 1},
    {isLeftEdge,        false, isLeftOf,          true,  -(NUM_COLS+1)},
    {isRightEdge,       false, isRightOf,         true,  -(NUM_COLS-1)},
    {isLeftEdge,        false, isLeftOf,          true,  (NUM_COLS-1)},
    {isRightEdge,       false, isRightOf,         true,  (NUM_COLS+1)},
    {0},
};


That made it much easier to write the last types of blocks (i.e. left, right, and diagonal).

Of course, I learned a lot about factoring out patterns by learning Lisp and Scheme, specifically reading and watching SICP.

Name: Anonymous 2008-04-23 23:52

>>6
I know what syntactic sugar is. I know that technically the brackets wouldn't be syntactic salt, but to me they would be because they would be useless, and would actually make the code look worse to me.

And, actually, I'd never heard of the n-queens problem, but my program doesn't really do that. I've used my program to show that an arrangement of 5 queens is enough to block the entire board, though :\

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List