Thursday, May 7, 2009

Lab 9: Eight Queens

For the past few days I have been working on a C++ assignment in my "Intro to Programming II" class at school. Up until now these labs have been fairly simple to handle with a bit of logical thinking and an understanding of what needs to get done in order for the program to work correctly. Lab 9 is a bit tough and only a few people in the class have done it. Many people have just decided to skip it altogether, but I'm a stubborn programmer.

The gist of the assignment is to write a program which will place eight queens on an 8x8 chessboard. The catch is that the queens have to be placed so that none of them would be able to take some other queen in one move.

My current program is on the computer at school, so I'll update this post with my (very rough draft-esque) code.

Update:
The code as of 5/8/09
http://www.mediafire.com/file/nojt5251wlf/lab 9 eight queens.cpp
(see update 3)

It works up until the program runs into a dead end in the recursive function, where it just stops instead of returning to the previous column to try a different path. It shouldn't be too hard to fix once I find out why exactly the program stops.

Update2: So apparently the program runs fine on my computer (in Visual C++ 2008 and in Code::Blocks), but not in Xcode on my school's computers. Huh.


Update 3:
Yes! It works!
http://www.mediafire.com/download.php?nwyj3zc2cvi

It turns out that all I needed to fix the progran was "if (row>=8) return 1;"
The problem was that the function which checks up, down, left right, and the diagonals for queens makes a call to the 2d array "board[8][8]" (which represents the chessboard). On certain occasions, the program will try to check the element "board[8][x]" where x=8 which is impossible since that would mean the program is trying to check the ninth row (which doesn't exist), causing the program to end (apparently Code::Blocks isn't as picky about these sorts of things as Xcode is).

No comments:

Post a Comment