当前位置:首页 > JavaScript

蚁群算法js实现

2026-01-31 01:53:19JavaScript

蚁群算法简介

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

蚁群算法核心步骤

  1. 初始化参数

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

    • 每只蚂蚁根据信息素浓度和启发式信息(如距离倒数)选择下一个节点,直到完成完整路径。
  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实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounc…

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:CSS…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…