Coding Games and Programming Challenges to Code Better
Send your feedback or ask for help here!
Created by @Ondra77,validated by @Stef_3,@LeMasSon and @sblondeel.
If you have any issues, feel free to ping them.
Coding Games and Programming Challenges to Code Better
Send your feedback or ask for help here!
Created by @Ondra77,validated by @Stef_3,@LeMasSon and @sblondeel.
If you have any issues, feel free to ping them.
I already managed to handle a big part of the problem, but how can I check the diagonals?
def place():
global row
for r in row:
if r.count(β.β)==1:
r[r.index(β.β)]=βQβ
for i in range(8):
r=[row[i][x] for x in range(8)]
if r.count(β.β)==1:
row[i][r.index(β.β)]=βQβ
i used zip function to manage the diagonals
zip is fine, but if you want performance, there are better ways around β¦
I refactored my solution from using a Dictionary for blocked diagonals, to two boolean arrays to two bitmasks β¦
the arrays and bitmasks uses a fine trick related to NxN boards β¦ and that is that all diagonals share the same trait, for instance, for a queen placed on cell (3,3) β¦ the main diagonal from left to right will always have the same (row - col) value, (2-2), (1-1), (4-4) etc β¦
and for the other diagonal, it always has the same value (row + col), (2,4), (1,5), (0,6), (4,2) etc β¦
leveraging arrays with enough capacity to cover up the possible values as indices, or bitmasking for better optimization and compactness, you get a really easy and neat method to check diagonals and solve the problem !
If you think about it: Every diagonal has squares that are displaced by +n or -n units on the X and Y dimensions (so four combinations of +n and -n). You can use that to check for presence of an attacker on the diagonal. If youβre storing the board in an 8x8 array or an 8x1 array this can be done with a little basic math.