当前位置:首页 > JavaScript

蚁群算法js实现

2026-01-31 01:53:19JavaScript

蚁群算法简介

蚁群算法(Ant Colony Optimization, ACO)是一种模拟蚂蚁觅食行为的启发式算法,常用于解决组合优化问题(如旅行商问题TSP)。蚂蚁通过信息素(pheromone)标记路径,其他蚂蚁倾向于选择信息素浓度高的路径,最终找到最优解。

蚁群算法核心步骤

  1. 初始化参数

    蚁群算法js实现

    • 蚂蚁数量、迭代次数、信息素挥发系数、信息素重要程度因子(α)、启发函数重要程度因子(β)。
    • 初始化信息素矩阵和距离矩阵。
  2. 构建路径

    蚁群算法js实现

    • 每只蚂蚁根据信息素浓度和启发式信息(如距离倒数)选择下一个节点,直到完成完整路径。
  3. 更新信息素

    • 信息素挥发:所有路径的信息素按一定比例减少。
    • 信息素增强:蚂蚁在其经过的路径上释放信息素,路径越短释放越多。
  4. 迭代优化

    • 重复构建路径和更新信息素,直到达到最大迭代次数或收敛。

JavaScript实现示例(以TSP为例)

class AntColonyOptimization {
  constructor(distanceMatrix, antsCount = 10, iterations = 100, alpha = 1, beta = 2, evaporation = 0.5) {
    this.distanceMatrix = distanceMatrix; // 城市间距离矩阵
    this.antsCount = antsCount;          // 蚂蚁数量
    this.iterations = iterations;        // 迭代次数
    this.alpha = alpha;                  // 信息素重要程度
    this.beta = beta;                    // 启发式信息重要程度
    this.evaporation = evaporation;      // 信息素挥发率
    this.pheromone = Array(distanceMatrix.length).fill()
      .map(() => Array(distanceMatrix.length).fill(1)); // 初始化信息素矩阵
  }

  // 蚂蚁选择下一个城市
  selectNextCity(ant, visited) {
    const currentCity = ant.path[ant.path.length - 1];
    const unvisited = this.distanceMatrix.map((_, i) => i)
      .filter(i => !visited.has(i));

    // 计算转移概率
    const probabilities = unvisited.map(city => {
      const pheromone = Math.pow(this.pheromone[currentCity][city], this.alpha);
      const distance = 1 / this.distanceMatrix[currentCity][city];
      const heuristic = Math.pow(distance, this.beta);
      return pheromone * heuristic;
    });

    // 轮盘赌选择
    const sum = probabilities.reduce((a, b) => a + b, 0);
    const normalized = probabilities.map(p => p / sum);
    let random = Math.random();
    let index = 0;
    while (random > normalized[index]) {
      random -= normalized[index];
      index++;
    }
    return unvisited[index];
  }

  // 单次迭代
  runIteration() {
    const ants = Array(this.antsCount).fill().map(() => ({ path: [Math.floor(Math.random() * this.distanceMatrix.length)] }));
    let bestPath = null;
    let bestLength = Infinity;

    // 每只蚂蚁构建路径
    ants.forEach(ant => {
      const visited = new Set(ant.path);
      while (visited.size < this.distanceMatrix.length) {
        const nextCity = this.selectNextCity(ant, visited);
        ant.path.push(nextCity);
        visited.add(nextCity);
      }
      // 计算路径长度
      const length = ant.path.reduce((sum, city, i) => 
        sum + (i === 0 ? 0 : this.distanceMatrix[ant.path[i - 1]][city]), 0);
      if (length < bestLength) {
        bestLength = length;
        bestPath = [...ant.path];
      }
    });

    // 更新信息素
    this.pheromone = this.pheromone.map(row => row.map(val => val * this.evaporation));
    ants.forEach(ant => {
      const length = ant.path.reduce((sum, city, i) => 
        sum + (i === 0 ? 0 : this.distanceMatrix[ant.path[i - 1]][city]), 0);
      const pheromoneDelta = 1 / length;
      for (let i = 1; i < ant.path.length; i++) {
        const from = ant.path[i - 1];
        const to = ant.path[i];
        this.pheromone[from][to] += pheromoneDelta;
        this.pheromone[to][from] += pheromoneDelta; // 对称路径
      }
    });

    return { bestPath, bestLength };
  }

  // 主函数
  solve() {
    let globalBestPath = null;
    let globalBestLength = Infinity;
    for (let i = 0; i < this.iterations; i++) {
      const { bestPath, bestLength } = this.runIteration();
      if (bestLength < globalBestLength) {
        globalBestLength = bestLength;
        globalBestPath = bestPath;
      }
    }
    return { path: globalBestPath, length: globalBestLength };
  }
}

// 示例:4个城市的TSP问题
const distanceMatrix = [
  [0, 10, 15, 20],
  [10, 0, 35, 25],
  [15, 35, 0, 30],
  [20, 25, 30, 0]
];
const aco = new AntColonyOptimization(distanceMatrix);
const result = aco.solve();
console.log("最优路径:", result.path, "长度:", result.length);

参数调优建议

  • 蚂蚁数量:通常为城市数量的1-2倍。
  • α和β:α控制信息素影响(通常1-2),β控制启发式信息影响(通常2-5)。
  • 挥发系数:0.1-0.5,避免信息素积累过快导致局部最优。

应用扩展

  • 可调整distanceMatrix解决其他路径问题(如车辆路径问题VRP)。
  • 添加局部优化策略(如2-opt交换)提升解的质量。

标签: 算法js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个回…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码 funct…

js实现视口

js实现视口

js实现视口检测的方法 使用JavaScript检测元素是否进入视口(viewport)可以通过Intersection Observer API或手动计算元素位置实现。以下是两种常见方法: Int…

js 实现全选

js 实现全选

实现全选功能的方法 使用 JavaScript 实现全选功能通常需要操作复选框(checkbox)的状态。以下是几种常见的实现方式。 通过 DOM 操作实现全选 // 获取全选复选框和子复选…