q3part b
import java.util.Random;
public class TSPMutation {
public static void main(String[] args) {
// Example cities (0, 1, 2, 3, 4)
int[] chromosome = {0, 1, 2, 3, 4}; // A possible solution (tour)
System.out.println("Original Chromosome:");
printChromosome(chromosome);
// Apply Mutation (Swap two cities in the path)
mutate(chromosome);
System.out.println("Mutated Chromosome:");
printChromosome(chromosome);
}
// Mutation function: Swap two cities' positions
public static void mutate(int[] chromosome) {
Random rand = new Random();
// Randomly pick two distinct indices in the chromosome
int index1 = rand.nextInt(chromosome.length);
int index2 = rand.nextInt(chromosome.length);
// Ensure that the two indices are different
while (index1 == index2) {
index2 = rand.nextInt(chromosome.length);
}
// Swap the cities at the two indices
int temp = chromosome[index1];
chromosome[index1] = chromosome[index2];
chromosome[index2] = temp;
}
// Helper function to print the chromosome (tour)
public static void printChromosome(int[] chromosome) {
for (int city : chromosome) {
System.out.print(city + " ");
}
System.out.println();
}
}
Comments
Post a Comment