From 451b291b3e49d70c6bff64ccf305285025f0fc25 Mon Sep 17 00:00:00 2001 From: Safak Date: Thu, 19 Jun 2025 20:42:47 +0200 Subject: [PATCH] Flexible number of queens on field --- P2.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/P2.py b/P2.py index 78339d2..8eee8a8 100644 --- a/P2.py +++ b/P2.py @@ -64,11 +64,12 @@ class Field: for row in range(8, 0, -1): # (0:8] row_string = "" for line in range(8): - if row is self.state[line]: # is there a Queen in this line (spalte) in this row + if line < len(self.state) and row is self.state[line]: # is there a Queen in this line (spalte) in this row if (row + line) % 2 == 0: row_string += "▌Q▐│" else: row_string += " Q │" + elif (row + line) % 2 == 0: row_string += "███│" else: @@ -82,11 +83,11 @@ class Field: class Genetic: - def __init__(self): + def __init__(self, size=100): self.initial_population = [] - self.p_mutation = 0.1 + self.p_mutation = 0 - for i in range(100): + for i in range(size): self.initial_population.append(Field()) def random_selection(self, population): @@ -144,27 +145,33 @@ class Genetic: if child.get_fitness() > best_field.get_fitness(): best_field = child + if best_field.get_fitness() == 28: + break current_population = new_population new_population = [] - if best_field.get_fitness() == 28: - break return best_field + + + def main(): new_field = Field( - init_state=[6, 3, 5, 7, 1, 4, 2, 8]) # [8, 4, 5, 4, 4, 3, 7, 6] [5, 5, 5, 5, 1, 2, 8, 5] [6,3,5,7,1,4,2,8] + init_state=[1,2,3]) # [8, 4, 5, 4, 4, 3, 7, 6] [5, 5, 5, 5, 1, 2, 8, 5] [6,3,5,7,1,4,2,8] new_field.print_field() print(new_field.collisions()) - genetic = Genetic() - - best_genetic_field = genetic.genetic_algorithm(500) - + print("Genetic Algorithm") + genetic = Genetic(500) + best_genetic_field = genetic.genetic_algorithm(100) best_genetic_field.print_field() print(best_genetic_field.get_fitness()) + + + + main()