lundi 16 janvier 2017

Queens on chessboard solved randomly in python

I have a little program to write, but I got stuck. The idea is to try solve the "queen problem" by totally placing the queenst totally random in each row of the chess board, and see how many repetitions it takes to solve it. The chess board can be any size

My idea is to create s lists, each containing s "empty" characters (underscores). Then for each line randomly pick a position to insert the queen ("I" value) and then mark all the positions below and diagonally down (i'm going row-by-row, so I don't have to bother about rows above) with X. if in any iteration the randomly chosen position for the queen matches with position of any X in that row, I start the new chessboard from scratch. I have something like this, but I don't know how to finish it. Could anyone please help?

s = input ("Enter board size\n")
s = int(s)

board = [[_ for x in range(s)] for y in range(s)] 


for y in range (0, s-1):
    pos = randint(0,s-1)    #randomly choose queen position
    if board[y][pos] =! ("X"):  #X value is for the "blocked" position
        board[y][pos] = ("I")   #I value is a queen
        for z in range (y, s-2):
            board[z + 1] = ("X")
            board[z + 1][pos - 1] = ("X")
            board[z + 1][pos + 1] = ("X")


#print out the board
for y in range (0, s-1):
    print (board[y])




Aucun commentaire:

Enregistrer un commentaire