Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
3.7 kB
0
Indexable
Never
import random
import string 

MyString = "Dan_Ling*0918273645"
population = 1000  # population size
pc = 0.7
pm = 0.1
B = 8 # number of bits
length = len(MyString)

def generate_random_string():
    parts = MyString.split('_')
    first_name = parts[0]
    last_name, student_id = parts[1].split('*')

    first_name_length = len(first_name)
    last_name_length = len(last_name)
    student_id_length = len(student_id)

    generated_first_name = ''.join(random.choice(string.ascii_letters) for _ in range(first_name_length))
    generated_last_name = ''.join(random.choice(string.ascii_letters) for _ in range(last_name_length))
    generated_student_id = ''.join(random.choice(string.digits) for _ in range(student_id_length))

    generated_string = f"{generated_first_name}_{generated_last_name}*{generated_student_id}"
    
    return generated_string

def crossover(parent1, parent2):
    crossover_point = random.randint(0, length - 1) 
    child1 = parent1[:crossover_point] + parent2[crossover_point:]
    child2 = parent2[:crossover_point] + parent1[crossover_point:]
    return child1, child2

def mutation(child1, child2):
    mutationPoint = random.randint(0, len(child1) - 1)  
    mutated_child1, mutated_child2 = list(child1), list(child2)
    mutated_child1[mutationPoint] = "1" if mutated_child1[mutationPoint] == "0" else "0"
    mutated_child2[mutationPoint] = "1" if mutated_child2[mutationPoint] == "0" else "0"
    mutated_child1 = ''.join(mutated_child1) 
    mutated_child2 = ''.join(mutated_child2)

    return mutated_child1, mutated_child2

def fitness(input_string, target_string):
    fit_score = sum(1 for i in range(length) if input_string[i] == target_string[i])
    fitness = fit_score / length
    return fitness

# Generate initial population
individuals = [generate_random_string() for _ in range(population)]

# Evolution loop over generations
for generation in range(100):  

    print(f"Generation {generation + 1} bit strings:")
    for ind in individuals:
        bit_string = ''.join(format(ord(char), '08b') for char in ind)
        print(f"Random Generated String: {ind}, Bit String: {bit_string}")

  
    fitness_scores = [fitness(individual, MyString) for individual in individuals]

    # Check if any individual matches the target string
    for i, individual in enumerate(individuals):
        if individual == MyString:
            print(f"Perfect match found in generation {generation + 1}!")
            print(f"Individual: {individual}, Fitness: {fitness_scores[i]}")
            exit()  # Terminate the program

    # Sort individuals based on fitness scores
    sorted_individuals = [individual for _, individual in sorted(zip(fitness_scores, individuals), reverse=True)]

    # Keep the top 100 fittest individuals
    individuals = sorted_individuals[:population]

    # Perform crossover and mutation
    new_individuals = []
    for _ in range(population // 2):
        parent1 = random.choice(individuals)
        parent2 = random.choice(individuals)
        child1, child2 = crossover(parent1, parent2)
        mutated_child1, mutated_child2 = mutation(child1, child2)
        new_individuals.append(mutated_child1)
        new_individuals.append(mutated_child2)

    # Append mutated children to the population
    individuals.extend(new_individuals)

    # Keep only the top 100 fittest individuals after appending mutated children
    fitness_scores = [fitness(individual, MyString) for individual in individuals]
    sorted_individuals = [individual for _, individual in sorted(zip(fitness_scores, individuals), reverse=True)]
    individuals = sorted_individuals[:population]
Leave a Comment