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.
But after doing this for the first couple types of blocks, I realized that I could factor a pattern out of it.
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.
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.
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.