C/C++,优化算法——使用遗传算法的旅行商问题(traveling-salesman-problem)的源程序

1 文本格式

#include <bits/stdc++.h>
#include <limits.h>
using namespace std;

// Number of cities in TSP
#define V 5

// Names of the cities
#define GENES ABCDE

// Starting Node Value
#define START 0

// Initial population size for the algorithm
#define POP_SIZE 10

// Structure of a GNOME
// string defines the path traversed
// by the salesman while the fitness value
// of the path is stored in an integer

struct individual {
    string gnome;
    int fitness;
};

// Function to return a random number
// from start and end
int rand_num(int start, int end)
{
    int r = end - start;
    int rnum = start + rand() % r;
    return rnum;
}

// Function to check if the character
// has already occurred in the string
bool repeat(string s, char ch)
{
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ch)
            return true;
    }
    return false;
}

// Function to return a mutated GNOME
// Mutated GNOME is a string
// with a random interchange
// of two genes to create variation in species
string mutatedGene(string gnome)
{
    while (true) {
        int r = rand_num(1, V);
        int r1 = rand_num(1, V);
        if (r1 != r) {
            char temp = gnome[r];
            gnome[r] = gnome[r1];
            gnome[r1] = temp;
            break;
        }
    }
    return gnome;
}

// Function to return a valid GNOME string
// required to create the population
string create_gnome()
{
    string gnome = "0";
    while (true) {
        if (gnome.size() == V) {
            gnome += gnome[0];
            break;
        }
        int temp = rand_num(1, V);
        if (!repeat(gnome, (char)(temp + 48)))
            gnome += (char)(temp + 48);
    }
    return gnome;
}

// Function to return the fitness value of a gnome.
// The fitness value is the path length
// of the path represented by the GNOME.
int cal_fitness(string gnome)
{
    int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },
                    { 2, 0, 4, 8, INT_MAX },
                    { INT_MAX, 4, 0, 3, 3 },
                    { 12, 8, 3, 0, 10 },
                    { 5, INT_MAX, 3, 10, 0 } };
    int f = 0;
    for (int i = 0; i < gnome.size() - 1; i++) {
        if (map[gnome[i] - 48][gnome[i + 1] - 48] == INT_MAX)
            return INT_MAX;
        f += map[gnome[i] - 48][gnome[i + 1] - 48];
    }
    return f;
}

// Function to return the updated value
// of the cooling element.
int cooldown(int temp)
{
    return (90 * temp) / 100;
}

// Comparator for GNOME struct.
bool lessthan(struct individual t1,
            struct individual t2)
{
    return t1.fitness < t2.fitness;
}

// Utility function for TSP problem.
void TSPUtil(int map[V][V])
{
    // Generation Number
    int gen = 1;
    // Number of Gene Iterations
    int gen_thres = 5;

    vector<struct individual> population;
    struct individual temp;

    // Populating the GNOME pool.
    for (int i = 0; i < POP_SIZE; i++) {
        temp.gnome = create_gnome();
        temp.fitness = cal_fitness(temp.gnome);
        population.push_back(temp);
    }

    cout << "\nInitial population: " << endl
        << "GNOME     FITNESS VALUE\n";
    for (int i = 0; i < POP_SIZE; i++)
        cout << population[i].gnome << " "
        << population[i].fitness << endl;
    cout << "\n";

    bool found = false;
    int temperature = 10000;

    // Iteration to perform
    // population crossing and gene mutation.
    while (temperature > 1000 && gen <= gen_thres) {
        sort(population.begin(), population.end(), lessthan);
        cout << "\nCurrent temp: " << temperature << "\n";
        vector<struct individual> new_population;

        for (int i = 0; i < POP_SIZE; i++) {
            struct individual p1 = population[i];

            while (true) {
                string new_g = mutatedGene(p1.gnome);
                struct individual new_gnome;
                new_gnome.gnome = new_g;
                new_gnome.fitness = cal_fitness(new_gnome.gnome);

                if (new_gnome.fitness <= population[i].fitness) {
                    new_population.push_back(new_gnome);
                    break;
                }
                else {

                    // Accepting the rejected children at
                    // a possible probability above threshold.
                    float prob = pow(2.7,
                        -1 * ((float)(new_gnome.fitness
                            - population[i].fitness)
                            / temperature));
                    if (prob > 0.5) {
                        new_population.push_back(new_gnome);
                        break;
                    }
                }
            }
        }

        temperature = cooldown(temperature);
        population = new_population;
        cout << "Generation " << gen << " \n";
        cout << "GNOME     FITNESS VALUE\n";

        for (int i = 0; i < POP_SIZE; i++)
            cout << population[i].gnome << " "
            << population[i].fitness << endl;
        gen++;
    }
}

int main()
{

    int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },
                    { 2, 0, 4, 8, INT_MAX },
                    { INT_MAX, 4, 0, 3, 3 },
                    { 12, 8, 3, 0, 10 },
                    { 5, INT_MAX, 3, 10, 0 } };
    TSPUtil(map);
}
 

2 代码格式

#include <bits/stdc++.h>
#include <limits.h>
using namespace std;// Number of cities in TSP
#define V 5// Names of the cities
#define GENES ABCDE// Starting Node Value
#define START 0// Initial population size for the algorithm
#define POP_SIZE 10// Structure of a GNOME
// string defines the path traversed
// by the salesman while the fitness value
// of the path is stored in an integerstruct individual {string gnome;int fitness;
};// Function to return a random number
// from start and end
int rand_num(int start, int end)
{int r = end - start;int rnum = start + rand() % r;return rnum;
}// Function to check if the character
// has already occurred in the string
bool repeat(string s, char ch)
{for (int i = 0; i < s.size(); i++) {if (s[i] == ch)return true;}return false;
}// Function to return a mutated GNOME
// Mutated GNOME is a string
// with a random interchange
// of two genes to create variation in species
string mutatedGene(string gnome)
{while (true) {int r = rand_num(1, V);int r1 = rand_num(1, V);if (r1 != r) {char temp = gnome[r];gnome[r] = gnome[r1];gnome[r1] = temp;break;}}return gnome;
}// Function to return a valid GNOME string
// required to create the population
string create_gnome()
{string gnome = "0";while (true) {if (gnome.size() == V) {gnome += gnome[0];break;}int temp = rand_num(1, V);if (!repeat(gnome, (char)(temp + 48)))gnome += (char)(temp + 48);}return gnome;
}// Function to return the fitness value of a gnome.
// The fitness value is the path length
// of the path represented by the GNOME.
int cal_fitness(string gnome)
{int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },{ 2, 0, 4, 8, INT_MAX },{ INT_MAX, 4, 0, 3, 3 },{ 12, 8, 3, 0, 10 },{ 5, INT_MAX, 3, 10, 0 } };int f = 0;for (int i = 0; i < gnome.size() - 1; i++) {if (map[gnome[i] - 48][gnome[i + 1] - 48] == INT_MAX)return INT_MAX;f += map[gnome[i] - 48][gnome[i + 1] - 48];}return f;
}// Function to return the updated value
// of the cooling element.
int cooldown(int temp)
{return (90 * temp) / 100;
}// Comparator for GNOME struct.
bool lessthan(struct individual t1,struct individual t2)
{return t1.fitness < t2.fitness;
}// Utility function for TSP problem.
void TSPUtil(int map[V][V])
{// Generation Numberint gen = 1;// Number of Gene Iterationsint gen_thres = 5;vector<struct individual> population;struct individual temp;// Populating the GNOME pool.for (int i = 0; i < POP_SIZE; i++) {temp.gnome = create_gnome();temp.fitness = cal_fitness(temp.gnome);population.push_back(temp);}cout << "\nInitial population: " << endl<< "GNOME     FITNESS VALUE\n";for (int i = 0; i < POP_SIZE; i++)cout << population[i].gnome << " "<< population[i].fitness << endl;cout << "\n";bool found = false;int temperature = 10000;// Iteration to perform// population crossing and gene mutation.while (temperature > 1000 && gen <= gen_thres) {sort(population.begin(), population.end(), lessthan);cout << "\nCurrent temp: " << temperature << "\n";vector<struct individual> new_population;for (int i = 0; i < POP_SIZE; i++) {struct individual p1 = population[i];while (true) {string new_g = mutatedGene(p1.gnome);struct individual new_gnome;new_gnome.gnome = new_g;new_gnome.fitness = cal_fitness(new_gnome.gnome);if (new_gnome.fitness <= population[i].fitness) {new_population.push_back(new_gnome);break;}else {// Accepting the rejected children at// a possible probability above threshold.float prob = pow(2.7,-1 * ((float)(new_gnome.fitness- population[i].fitness)/ temperature));if (prob > 0.5) {new_population.push_back(new_gnome);break;}}}}temperature = cooldown(temperature);population = new_population;cout << "Generation " << gen << " \n";cout << "GNOME     FITNESS VALUE\n";for (int i = 0; i < POP_SIZE; i++)cout << population[i].gnome << " "<< population[i].fitness << endl;gen++;}
}int main()
{int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },{ 2, 0, 4, 8, INT_MAX },{ INT_MAX, 4, 0, 3, 3 },{ 12, 8, 3, 0, 10 },{ 5, INT_MAX, 3, 10, 0 } };TSPUtil(map);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/202283.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HDFS 3.x 数据存储新特性-纠删码

HDFS是⼀个⾼吞吐、⾼容错的分布式⽂件系统,但是HDFS在保证⾼容错的同时也带来⾼昂的存储成本,⽐如有5T的数据存储在HDFS上,按照HDFS的默认3副本机制,将会占⽤15T的存储空间。那么有没有⼀种能达到和副本机制相同的容错能⼒但是能⼤幅度降低存储成本的机制呢,有,就是在HD…

ahk系列-windows超级运行框-表达式计算(12)—功能汇总

1、环境准备 windows 7&#xff0c;8&#xff0c;10&#xff0c;11操作系统ahk 2.x_64位翻译功能需要联网使用 2、使用方式 输入winR打开windows运行框 get/getpath 命令获取配置文件环境变量set/sets 设置 “用户/系统” 环境变量或者pathencode/decode 中文编码和解码len…

【算法题】一种字符串压缩表示的解压(js)

输入&#xff1a;2dff 输出 !error 两个d不需要压缩&#xff0c;故输入不合法 输入:4eA 输出:!error 全部由小写英文字母组成&#xff0c;压缩后不会出现&#xff0c;故输出不合法 function solution(str) {const error "!error";// 只能包含小写字母和数字 [^a-z0…

详解线段树

前段时间写过一篇关于树状数组的博客树状数组&#xff0c;今天我们要介绍的是线段树&#xff0c;线段树比树状数组中的应用场景更加的广泛。这些问题也是在leetcode 11月的每日一题频繁遇到的问题&#xff0c;实际上线段树就和红黑树 、堆一样是一类模板&#xff0c;但是标准库…

【荣誉】科东软件荣获广州市软件行业协会双料大奖!

软件产业在数字经济中扮演着基础支撑的角色&#xff0c;对于优化产业结构、提高自主可控、赋能整体经济高质量发展具有关键作用。 近日&#xff0c;广州市软件行业第七届会员大会第三次会议成功召开&#xff01;此次会议旨在回顾过去一年的行业发展&#xff0c;展望未来的趋势和…

React useCallback 详解

在 React 中&#xff0c;useCallback 是一个非常实用的 Hook&#xff0c;它可以帮助我们避免在每次渲染时都创建新的函数&#xff0c;从而提高性能。useCallback 返回一个记忆化的回调函数&#xff0c;它只在其依赖项改变时才会改变。 下面是一个详细的 React useCallback 教程…

nginx编译安装及配置文件的修改

编译安装nginx 1.关闭防火墙&#xff0c;安全机制&#xff0c;去官网下载nginx压缩包&#xff0c;并进行解压 systemctl stop firewalld #关闭防火墙 systemctl disable --now firewalld #开机不自启并立即关闭防火墙 setenforce 0 #关闭安全机制 2.安装依赖包&#xff0…

CSU计算机学院2023秋C语言期中题目思路分享(前三道题)

文章目录 写在前面A&#xff1a;个税计算——阅读理解与数据类型转换原题输入输出样例输入样例输出 题目分析题目理解代码实现与问题解决 我的代码 B&#xff1a;时制转换——问题是一点点解决的原题输入输出样例输入样例输出 题目分析我的代码 C&#xff1a;统计进位——人教版…

编程语言分类

如果要将编程语言分成两大类&#xff0c;可以考虑以下分类方式&#xff1a; 编译型语言&#xff08;Compiled Languages&#xff09;&#xff1a;这类语言在运行之前需要通过编译器将源代码转换为机器码或类似形式的可执行代码。编译型语言的特点包括&#xff1a; 需要显式的编…

用PHP与html做一个简单的登录页面

用PHP与html做一个简单的登录页面 login.html的设计 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title&…

我一人全干!之二,vue3后台管理系统树形目录的实现。

一个完整的后台管理系统需要一个树形结构的目录&#xff0c;方便用户切换页面。 因为使用的是element-plus的ui库&#xff0c;所以首选el-menu组件&#xff0c;点击查看文档。 因为此组件不是树形结构的&#xff0c;所以需要封装成系统需要的树形结构组件。可以使用vue的递归组…

探索鸿蒙_ArkTs开发语言

ArkTs 在正常的网页开发中&#xff0c;实现一个效果&#xff0c;需要htmlcssjs三种语言实现。 但是使用ArkTs语言&#xff0c;就能全部实现了。 ArkTs是基于TypeScript的&#xff0c;但是呢&#xff0c;TypeScript是基于javascript的&#xff0c;所以ArkTs不但能完成js的工作&a…

传导电流密度方向与磁矢位方向相同

矢量位 A ⃗ \vec A A 由于磁感应强度 B ⃗ \vec B B 是无源场&#xff0c;散度为0&#xff0c; ∇ ⋅ B ⃗ 0 \nabla \cdot \vec B 0 ∇⋅B 0, 因此引入矢量位 A ⃗ \vec A A , 满足 ∇ A ⃗ B ⃗ \begin{align} \nabla \times \vec A &\vec B \end{align} ∇A ​B ​…

Vue3 Element-Plus 一站式生成动态表单:简化前端开发流程

文章目录 1. 引言2. Vue3 和 Element-Plus 简介2.1 Vue32.2 Element-Plus 3. 动态表单的需求与挑战4. Vue3 和 Element-Plus 动态表单的优势4.1 Vue3的组合式API4.2 Element-Plus的表单组件 5. 一站式生成动态表单的实现5.1 准备工作5.2 创建动态表单组件5.3 使用动态表单组件 …

在开发软件KEIL MDK和IAR开发工程里面打印行号、文件名、函数名、时间

最近应用固件没有时间记录&#xff0c;分别请那个是最新的&#xff08;在没有版本区别的情况下&#xff09;&#xff0c;有个办法记录编译时间即可&#xff0c;记录笔记以便查看 在软件工程里面直接用宏 __FILE __ 当前程序文件名的字符串 __FUNCTION __ 当前函数的名字字符串 …

2023年2月8日 Go生态洞察:Profile-Guided Optimization预览

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…

优化的 MCM-GPU 比具有相同 SM 总数和 DRAM 带宽的同等配备的多 GPU 系统快 26.8%。

MCM-GPU: Multi-chip-module GPUs for Continued Performance Scalability 抽象&#xff1a; 从历史上看&#xff0c;基于 GPU 的高性能计算的改进与晶体管缩放紧密相连。随着摩尔定律的减慢&#xff0c;每个芯片的晶体管数量不再以历史速度增长&#xff0c;单个单片GPU的性能…

易点易动设备管理系统--提升设备能耗管理效率的工具

在当今的节能环保意识日益增强的社会背景下&#xff0c;设备能耗管理成为了市场推广人员关注的焦点之一。为了帮助市场推广人员提升设备能耗管理效率&#xff0c;易点易动设备管理系统应运而生。本文将详细介绍易点易动设备管理系统的功能和优势&#xff0c;以及如何借助该系统…

Python-元组详解

注意&#xff1a;列表是方括号【】&#xff0c;元组是圆括号&#xff08;&#xff09;&#xff0c;这里要分清。 创建元组 1、a () 2、b tuple() a () b tuple() 2、可以指定初始值 a (1,2,3,4) a (1,2,3,4) 3、元素可以是任意类型 a (1,2,3,4,hello) a (1,2,3,4…

2023年12月实时获取地图边界数据方法,省市区县街道多级联动【附实时geoJson数据下载】

首先&#xff0c;来看下效果图 在线体验地址&#xff1a;https://geojson.hxkj.vip&#xff0c;并提供实时geoJson数据文件下载 可下载的数据包含省级geojson行政边界数据、市级geojson行政边界数据、区/县级geojson行政边界数据、省市区县街道行政编码四级联动数据&#xff0…