You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript读取TSP库文件并提取坐标存入对应数组

JavaScript读取TSP文件提取坐标的实现方案

核心解析逻辑

该逻辑适配你给出的TSP标准格式,通过标记位锁定坐标段范围,避免解析到头部无关信息:

function parseTsp(text) {
  const node = [];
  const x = [];
  const y = [];
  const lines = text.split('\n');
  // 标记是否进入坐标数据段
  let inCoordSection = false;

  for (const line of lines) {
    const trimLine = line.trim();
    // 遇到结束标记直接终止遍历
    if (trimLine === 'EOF') break;
    // 匹配到坐标段起始标记,切换状态后跳过当前行
    if (trimLine === 'NODE_COORD_SECTION') {
      inCoordSection = true;
      continue;
    }
    // 仅处理坐标段内的非空行
    if (inCoordSection && trimLine) {
      // 按任意空白符分割后转数字
      const [nodeId, xVal, yVal] = trimLine.split(/\s+/).map(Number);
      node.push(nodeId);
      x.push(xVal);
      y.push(yVal);
    }
  }
  return { node, x, y };
}

不同场景调用方式

1. Node.js环境读取本地文件

const fs = require('fs');
// 替换为你的tsp文件路径
fs.readFile('./file1.tsp', 'utf8', (err, text) => {
  if (err) {
    console.error('文件读取失败:', err);
    return;
  }
  const { node, x, y } = parseTsp(text);
  // 此处可使用拿到的三个数组做后续处理
  console.log(node, x, y);
});

2. 浏览器端用户上传文件解析

页面上传控件:

<input type="file" id="tspUpload" accept=".tsp">

交互逻辑:

document.getElementById('tspUpload').addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = (event) => {
    const text = event.target.result;
    const { node, x, y } = parseTsp(text);
    // 此处可使用拿到的三个数组做后续处理
    console.log(node, x, y);
  };
  reader.readAsText(file);
});

内容的提问来源于stack exchange,提问作者tspnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:06:05