Created
December 10, 2022 15:25
-
-
Save deleteman/74c9e2b19e6312d321bf5df9cbb6e5a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const NUM_CITIES = 10; // number of cities in the sales route | |
const POPULATION_SIZE = 100; // number of individuals in the population | |
const MUTATION_RATE = 0.1; // probability of mutation | |
const CROSSOVER_RATE = 0.7; // probability of crossover | |
const MAX_ITERATIONS = 1000; // maximum number of iterations | |
// define the distance between each pair of cities | |
const distances = [ [0, 10, 15, 20, 25, 30, 35, 40, 45, 50], | |
[10, 0, 5, 10, 15, 20, 25, 30, 35, 40], | |
[15, 5, 0, 5, 10, 15, 20, 25, 30, 35], | |
[20, 10, 5, 0, 5, 10, 15, 20, 25, 30], | |
[25, 15, 10, 5, 0, 5, 10, 15, 20, 25], | |
[30, 20, 15, 10, 5, 0, 5, 10, 15, 20], | |
[35, 25, 20, 15, 10, 5, 0, 5, 10, 15], | |
[40, 30, 25, 20, 15, 10, 5, 0, 5, 10], | |
[45, 35, 30, 25, 20, 15, 10, 5, 0, 5], | |
[50, 40, 35, 30, 25, 20, 15, 10, 5, 0], | |
]; | |
// create the initial population | |
let population = []; | |
for (let i = 0; i < POPULATION_SIZE; i++) { | |
// generate a random individual | |
let individual = []; | |
for (let j = 0; j < NUM_CITIES; j++) { | |
individual.push(j); | |
} | |
// shuffle the cities in the individual | |
for (let j = 0; j < NUM_CITIES; j++) { | |
let k = Math.floor(Math.random() * NUM_CITIES); | |
let temp = individual[j]; | |
individual[j] = individual[k]; | |
individual[k] = temp; | |
} | |
population.push(individual); | |
} | |
// define a function to calculate the fitness of an individual | |
const calculateFitness = (individual) => { | |
let fitness = 0; | |
for (let i = 0; i < NUM_CITIES - 1; i++) { | |
let city1 = individual[i]; | |
let city2 = individual[i + 1]; | |
fitness += distances[city1][city2]; | |
} | |
return fitness; | |
}; | |
// define a function to select individuals for the next generation | |
const selection = (population) => { | |
// calculate the fitness of each individual | |
let fitnesses = population.map(calculateFitness); | |
// normalize the fitness values | |
let totalFitness = fitnesses.reduce((a, b) => a + b, 0); | |
let probabilities = fitnesses.map((fitness) => fitness / totalFitness); | |
// select individuals for the next generation | |
let nextGeneration = []; | |
for (let i = 0; i < POPULATION_SIZE; i++) { | |
// choose two individuals based on their probabilities | |
let individual1 = Math |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment