import random import copy import pickle import numpy # Constants GRID_SIZE = 5 PLANT_TYPES = [1, 2, 3] POPULATION_SIZE = 1000 MAX_GENERATIONS = 100 MUTATION_RATE = 0.1 def generate_random_chromosome(): # Generate a random chromosome (random matrix) chromosome = [[0] * GRID_SIZE for _ in range(GRID_SIZE)] for row in range(GRID_SIZE): for col in range(GRID_SIZE): available_types = PLANT_TYPES.copy() chromosome[row][col] = random.choice(available_types) return chromosome def calculate_fitness(chromosome): # Calculate the fitness by counting the number of adjacent fields with the same plant type fitness = 0 appearances = [0,0,0] for row in range(GRID_SIZE): for col in range(GRID_SIZE): plant_type = chromosome[row][col] # Check left neighbor if col > 0 and chromosome[row][col - 1] == plant_type: fitness += 1 # Check top neighbor if row > 0 and chromosome[row - 1][col] == plant_type: fitness += 1 for row in chromosome: appearances[0] = appearances[0] + row.count(1) appearances[1] = appearances[1] + row.count(2) appearances[2] = appearances[2] + row.count(3) for i in range(len(appearances)): if appearances[i] < 7 and appearances[i] > 9: fitness = fitness + abs(appearances[i]-8) return fitness def selection(population): # Perform tournament selection to choose parents for reproduction tournament_size = 5 parents = [] for _ in range(len(population)): tournament = random.sample(population, tournament_size) tournament.sort(key=lambda chromosome: calculate_fitness(chromosome)) parents.append(tournament[0]) return parents def crossover(parent1, parent2): # Perform single-point crossover to create two offspring crossover_point = random.randint(0, (GRID_SIZE*GRID_SIZE)-1) row = crossover_point // GRID_SIZE column = crossover_point % GRID_SIZE offspring1 = [] offspring2 = [] counter = 0 while counter