Hello, I am trying to put numerical values in a table-matrix where, when it is 4x4, 6x6 or 8x8, the user puts the corresponding queens in positions that one wants (according to the expansion or growth, if he wants it to be 4x4, he can only put 4 with 6x6 put 6) that they are seen with the 'X' symbol in the boxes you want and the rest of the boxes are considered 0 and that it is not using the random function in a random way that it is as the user puts it I don't know if can as it is written in the function or it has to be one by one. This is the code I am using:
import random
# <============================== functions ==============================> #
# it will create a initial state of queens for us :
Reyna= int(input("Cuantas Reinas desea Usar(Solo se aceptan Numeros Pares no Impares) "))
def randomRestart():
columnList = [0] * Reyna
for col in range(Reyna):
columnList[col] = random.randint(1, Reyna)
return columnList
def printBoard(columnList):
for row in range(Reyna, 0, -1):
for col in range(Reyna):
if columnList[col] == row:
print("X", end=" ")
else:
print(0, end=" ")
print()
queensPositions = randomRestart()
print("Posicion de Columnas de Las Reinas : ", queensPositions)
print("Posicion Inicial de las Reinas: ")
print('\n***********************\n')
printBoard(queensPositions)
print('\n***********************\n')
print("==========================================================================")
If I understand correctly what you want then one loop
for
should be enough to fill the board.In the previous code we only ask the user to enter the number of queens and we generate a matrix that will correctly represent the board, for this we use a list compression which is an abbreviated way of writing a cycle
for
.The next step is to use a loop
for
to ask the user to enter the positions they want the queens to go on the board.With the previous code we ask you to enter the row and column where you want the queen to go, in that position we place the
X
, this will be repeated according to the number of queens that the user has entered. That cycle still needs to validate if the position is correct, but I'll leave that to you.As you mentioned in the comments that you wanted to save the number of the column where the queens are located, so all we have to do is save the variable
columna
that is in the for loop in another list, it would be something like this:An observation, if 2 queens are placed in the same column then the list
columnas_reynas
will have duplicate data, if you will use the list later and you do not need duplicates then you can docolumnas_reynas = list(set(columnas_reynas))
, what it doesset
is eliminate duplicates. Or if you think it's better you can save the positionx
andy
the queen, doingcolumnas_reynas.append((fila, columna))
so and you will have a list of tuples. If you have any questions, leave them in the comments :D.