2 ms·
I remember Byte(?) magazine had a contest to create the coolest 8-queens solver. I wrote a BASIC(!) program that represented the board as a string of 8 digits,
by JoeAltmaier 4y ago
I remember Byte(?) magazine had a contest to create the coolest 8-queens solver.
I wrote a BASIC(!) program that represented the board as a string of 8 digits, 1 thru 8. Each digit represented the height of the queen in that column.
See, there could only be one queen per column, so one character per column was enough. And there could only be one queen per row, so they would all have different row numbers, thus the digits have to be 1 thru 8.
Then it permuted the digits in a simple double loop. Each permutation was tested by comparing each digit with the other digits to it's left, and seeing if the distance between the digit positions was equal to the (absolute value of) the difference between the digit values. That would mean they were on a diagonal. Queens can capture on the diagonal.
The best trick was, when a digit failed the 'difference test' the permutation was pruned from that point. So the entire permutation tree didn't have to be traversed.
On an old sub-MHz HP2000 processor the program took 20 minutes to complete and printed all the correct 8-queen arrangements.
This solution seemed to me to be pretty obvious, so I didn't submit it.
In the next issue of the magazine, every single solution presented represented the board as an 8X8 array. They all struggled to place 'queens' at positions in the array and tediously tests every cell to the left,right,up,down and four diagonals.
They all took hours to complete execution.