% تعریف ماتریس فاصله بین شهرها
distance = [...]; % ماتریس فاصله
% تعریف تعداد شهرها
num_cities = size(distance, 1);
% تعداد جمعیت و تعداد نسلها
population_size = 50;
num_generations = 100;
% ایجاد جمعیت اولیه
population = zeros(population_size, num_cities);
for i = 1:population_size
population(i, :) = randperm(num_cities);
end
% تکامل جمعیت
for generation = 1:num_generations
% ارزیابی جمعیت
fitness = zeros(population_size, 1);
for i = 1:population_size
fitness(i) = calculate_fitness(population(i, :), distance);
end
% انتخاب والدین
parents = selection(population, fitness);
% تولید نسل جدید
offspring = crossover(parents);
% جایگزینی نسل جدید
population = replace(population, offspring);
end
% یافتن بهترین مسیر
best_route = population(1, :);
best_distance = calculate_fitness(best_route, distance);
function fitness = calculate_fitness(route, distance)
fitness = 0;
for i = 1:length(route)-1
fitness = fitness + distance(route(i), route(i+1));
end
fitness = fitness + distance(route(end), route(1));
end
function parents = selection(population, fitness)
[~, idx] = sort(fitness, 'ascend');
parents = population(idx(1:2), :);
end
function offspring = crossover(parents)
crossover_point = randi(length(parents(1, :)));
offspring = [parents(1, 1:crossover_point), parents(2, crossover_point+1:end)];
end
function new_population = replace(population, offspring)
new_population = population;
[~, idx] = min(arrayfun(@(i) calculate_fitness(offspring(i, :), distance), 1:size(offspring, 1)));
new_population(end, :) = offspring(idx, :);
end