
エリア・クラスタリング(grad)📒再まとめ📒☓
今までは1次元配列のデンドログラムをベースに考えていた。
決して悪いものではないのだが…
これは手作業で、隣接するエリアの結合・切断を行い、必要な台数の概算を決める仕組みだ。(厳密な配車はもう一段階必要になるが、大方の配車はこの程度しかやってない)
ただし、四色問題の様に隣接するエリアが3-4つになる地点ではどうしても矛盾が出てきてしまう。

豪雨のニュースを見ていて思いつく。荷両の多い地点を一般相対性理論みたいに見なして、地面の傾きをgradで見てもらえばいい。


後は、車格を自由に手配できるか、予め車格ごとに枠が決まっているかどうかだ。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>配車シミュレーター (Gradエンジン統合版)</title>
<style>
/* =========================================
共通・ベーススタイル
========================================= */
:root {
--bg-dark: #0B1420; --panel-dark: #121F2E; --line-dark: #1C2E3F;
--text-dark: #E7EDF3; --muted-dark: #8FA3B8;
--cut: #FF5C5C; --saddle: #7DF9FF; --conflict: #FF61D8;
}
body {
font-family: 'Segoe UI', "Hiragino Kaku Gothic ProN", "Noto Sans JP", sans-serif;
margin: 0; padding: 15px; background-color: #f0f2f5; color: #333;
height: 100vh; box-sizing: border-box; display: flex; flex-direction: column;
}
h2 { color: #2c3e50; font-size: 1.1em; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-top: 0; }
h3 { font-size: 0.95em; margin: 0 0 10px 0; color: #34495e; }
/* =========================================
3ペインレイアウト
========================================= */
.layout-container { display: flex; gap: 15px; height: 100%; align-items: stretch; overflow: hidden; }
.panel { background: #fff; border-radius: 8px; padding: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); display: flex; flex-direction: column; }
.panel-left { flex: 1.2; overflow-y: auto; }
.panel-center { flex: 1.5; background: #fafafa; border: 1px solid #e0e0e0; overflow-y: auto; display: flex; flex-direction: column; }
.panel-right { flex: 1.6; overflow-y: auto; }
/* =========================================
UIコンポーネント
========================================= */
.controls-box { margin-bottom: 15px; padding: 12px; background: #fff; border: 1px solid #bdc3c7; border-radius: 6px; }
.controls-box.active { border-color: #3498db; box-shadow: 0 0 6px rgba(52, 152, 219, 0.2); }
button { background: #3498db; color: #fff; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: bold; width: 100%; transition: 0.2s; }
button:hover { background: #2980b9; }
button.alt-btn { background: #2ecc71; margin-top: 10px; }
button.alt-btn:hover { background: #27ae60; }
button:disabled { background: #95a5a6; cursor: not-allowed; }
/* 左ペイン用トグル */
.mode-toggle { display: flex; gap: 10px; margin-bottom: 15px; }
.mode-toggle label { flex: 1; text-align: center; padding: 8px; border: 1px solid #bdc3c7; border-radius: 4px; cursor: pointer; background: #ecf0f1; font-weight: bold; font-size: 0.9em; transition: 0.2s;}
.mode-toggle input { display: none; }
.mode-toggle input:checked + label { background: #3498db; color: #fff; border-color: #3498db; }
/* テーブル共通 */
table { width: 100%; border-collapse: collapse; font-size: 0.85em; margin-bottom: 10px; background: #fff; }
th, td { border: 1px solid #ddd; padding: 7px; text-align: left; }
th { background-color: #ecf0f1; text-align: center; color: #2c3e50; position: sticky; top: 0; z-index: 1; }
td.center { text-align: center; }
td.num { text-align: right; font-weight: bold; }
.subtotal-row td { background-color: #e8f8f5; font-weight: bold; color: #16a085; }
.product-name { font-weight: bold; color: #34495e; }
/* 中央ペイン:モード別コントロール */
.mode-b-only, .mode-a-only { display: none; }
.fleet-input-table th { background-color: #d6eaf8; }
.fleet-input-table input { width: 50px; padding: 4px; text-align: center; border: 1px solid #bdc3c7; border-radius: 4px; font-size: 1em; }
/* Grad SVG マップ (中央ペイン下部) */
.svg-wrapper { flex: 1; background: var(--bg-dark); border-radius: 8px; position: relative; overflow: hidden; min-height: 350px; border: 1px solid var(--line-dark); }
svg { width: 100%; height: 100%; display: block; }
.ward-label { fill: #4A5C70; font-size: 10px; }
.svg-title { position: absolute; top: 10px; left: 10px; color: var(--text-dark); font-size: 12px; font-weight: bold; z-index: 2; pointer-events: none;}
.tooltip {
position: absolute; pointer-events: none; background: rgba(14,24,38,0.9); border: 1px solid var(--line-dark);
border-radius: 6px; padding: 6px 10px; font-size: 11px; line-height: 1.4; color: var(--text-dark);
transform: translate(-50%,-110%); white-space: nowrap; opacity: 0; transition: opacity .1s; z-index: 10;
}
.tooltip.show { opacity: 1; }
/* 右ペイン:配車結果 */
.truck-header { background: #34495e; color: #fff; font-weight: bold; }
.truck-header span { color: #f1c40f; }
.truck-header.error { background: #c0392b; }
.split-note { color: #e67e22; font-size: 0.85em; }
.summary-text { background: #fdf2e9; padding: 10px; border-left: 4px solid #e67e22; font-weight: bold; margin-bottom: 15px; font-size: 0.95em;}
</style>
</head>
<body>
<div class="layout-container">
<!-- ================= 左ペイン:データ設定 ================= -->
<div class="panel panel-left">
<h2>1. データ読込 & モード設定</h2>
<div class="controls-box">
<h3>計算モード</h3>
<div class="mode-toggle">
<input type="radio" name="mode" id="modeA" value="A" checked onchange="switchMode()">
<label for="modeA">モードA (フリー手配)</label>
<input type="radio" name="mode" id="modeB" value="B" onchange="switchMode()">
<label for="modeB">モードB (保有枠制限)</label>
</div>
<button onclick="generateData()">🎲 依頼データをランダム生成</button>
</div>
<table id="initialTable">
<thead>
<tr><th style="width:35%">品名</th><th style="width:35%">区</th><th style="width:30%">量</th></tr>
</thead>
<tbody id="initialBody">
<tr><td colspan="3" class="center">「データをランダム生成」を押してください</td></tr>
</tbody>
</table>
</div>
<!-- ================= 中央ペイン:Gradエンジン & コントロール ================= -->
<div class="panel panel-center">
<h2>2. 計算エンジン (Grad地形分析)</h2>
<!-- モードA用UI -->
<div class="controls-box mode-a-only" id="ctrlA">
<h3 style="margin:0 0 5px 0;">車格上限の指定</h3>
<div style="display:flex; align-items:center; gap:10px; font-size:0.9em;">
<label>手配可能な最大車格:
<select id="capSelectA" onchange="runModeA()" style="padding:4px;">
<option value="2">2t</option><option value="4">4t</option>
<option value="8">8t</option><option value="10">10t</option><option value="13" selected>13t</option>
</select>
</label>
<span style="color:#7f8c8d; font-size:0.85em;">※地形の合流が上限を超えると強制切断します</span>
</div>
</div>
<!-- モードB用UI -->
<div class="controls-box mode-b-only" id="ctrlB">
<h3 style="margin:0 0 5px 0;">手配台数入力</h3>
<p style="font-size:0.8em; margin:0 0 10px; color:#666;">Grad解析による理想枠が入力済です。実際の保有枠に修正して実行してください。</p>
<table class="fleet-input-table" style="margin-bottom:5px;">
<thead>
<tr>
<th>13t</th><th>10t</th><th>8t</th><th>6t</th><th>4t</th><th>2t</th>
</tr>
</thead>
<tbody>
<tr id="fleet-inputs-row">
<!-- JSで生成 -->
</tr>
</tbody>
</table>
<button class="alt-btn" id="btn-step3" onclick="runModeB_Execute()">この枠数で制約付き配車を実行</button>
</div>
<!-- Grad 描画領域 -->
<div class="svg-wrapper" id="svgWrap">
<div class="svg-title" id="svgTitle">地形トポロジー</div>
<svg id="mapSvg" viewBox="0 0 430 520"></svg>
<div class="tooltip" id="tooltip"></div>
</div>
</div>
<!-- ================= 右ペイン:配車結果 ================= -->
<div class="panel panel-right">
<h2>3. 最終配車リスト</h2>
<div id="result-summary"></div>
<table id="dispatchTable">
<tbody id="dispatchBody">
<tr><td colspan="4" class="center">計算結果がここに表示されます</td></tr>
</tbody>
</table>
</div>
</div>
<script>
// --- Grad エンジン定数・変数 ---
const WARDS = {"千代田":[0.5,-0.5],"中央":[2.0,-1.0],"港":[0.0,-4.5],"新宿":[-6.0,0.5],"文京":[-1.0,3.5],"豊島":[-5.0,5.5]};
const CAR_CLASSES = [13, 10, 8, 6, 4, 2];
const PALETTE = ["#F2B84B","#4FD1C5","#FF8B66","#A78BFA","#7C93C9","#B4E197","#F687B3","#94A3B8"];
const K = 4, BANDWIDTH = 2.5, TOL = 1e-9, TIE_EPS = 0.1;
const productTypes = ["食料品A", "飲料水B", "建材C", "雑貨D", "家電E", "衣類F", "部品G"];
const svgNS="http://www.w3.org/2000/svg";
function el(tag, attrs){ const e=document.createElementNS(svgNS,tag); for(const k in attrs) e.setAttribute(k, attrs[k]); return e; }
let currentMode = 'A';
let RAW = [], n, D, neighbors, height, gradParent, isCritical, saddleInfo, sx, sy;
// ==========================================
// 1. UI制御・初期化
// ==========================================
function switchMode() {
currentMode = document.querySelector('input[name="mode"]:checked').value;
document.querySelectorAll('.mode-a-only').forEach(el => el.style.display = currentMode === 'A' ? 'block' : 'none');
document.querySelectorAll('.mode-b-only').forEach(el => el.style.display = currentMode === 'B' ? 'block' : 'none');
if(RAW.length > 0) {
if(currentMode === 'A') runModeA();
else runModeB_Ideal();
}
}
function generateData() {
const pts = []; let id = 0;
for(const name in WARDS){
const [cx,cy] = WARDS[name];
const cnt = 3 + Math.floor(Math.random()*3); // 3-5 items per area
for(let k=0; k<cnt; k++){
const x = cx + (Math.random()*3-1.5);
const y = cy + (Math.random()*3-1.5);
const demand = +(0.5 + Math.random()*2.5).toFixed(1);
const pName = productTypes[Math.floor(Math.random()*productTypes.length)];
pts.push({id: id++, near: name, name: pName, x: +x.toFixed(2), y: +y.toFixed(2), demand: demand, w: demand});
}
}
RAW = pts;
computeGeometryAndGradient();
renderLeftTable();
if(currentMode === 'A') runModeA();
else runModeB_Ideal();
}
function renderLeftTable() {
const tbody = document.getElementById('initialBody');
tbody.innerHTML = '';
Object.keys(WARDS).forEach(ward => {
let items = RAW.filter(p => p.near === ward);
if(items.length === 0) return;
let total = 0;
items.forEach(p => {
total += p.demand;
tbody.innerHTML += `<tr><td class="product-name center">${p.name}</td><td class="center">${p.near}</td><td class="num">${p.demand.toFixed(1)} t</td></tr>`;
});
tbody.innerHTML += `<tr class="subtotal-row"><td colspan="2" class="center">【小計】 ${ward}</td><td class="num">${total.toFixed(1)} t</td></tr>`;
});
}
// ==========================================
// 2. Grad エンジン (共通コア)
// ==========================================
function computeGeometryAndGradient() {
n = RAW.length;
D = Array.from({length:n},()=>new Array(n).fill(0));
for(let i=0;i<n;i++)for(let j=0;j<n;j++) D[i][j]=Math.hypot(RAW[i].x-RAW[j].x, RAW[i].y-RAW[j].y);
neighbors = RAW.map((_,i)=>[...Array(n).keys()].filter(j=>j!==i).sort((a,b)=>D[i][a]-D[i][b]).slice(0,K));
height = RAW.map((_,i)=>{ let h=0; for(let j=0;j<n;j++) if(j!==i) h -= RAW[j].demand*Math.exp(-D[i][j]/BANDWIDTH); return h; });
gradParent = {}; isCritical=new Set(); saddleInfo={};
for(let i=0;i<n;i++){
const lower = neighbors[i].filter(j=>height[j] < height[i]-TOL);
if(lower.length===0){ isCritical.add(i); continue; }
const minh = Math.min(...lower.map(j=>height[j]));
const tied = lower.filter(j=>Math.abs(height[j]-minh)<TIE_EPS);
if(tied.length===1){ gradParent[i]=tied[0]; } else { saddleInfo[i]=tied; }
}
const xs=RAW.map(p=>p.x), ys=RAW.map(p=>p.y);
const xMin=Math.min(...xs)-1.4, xMax=Math.max(...xs)+1.4;
const yMin=Math.min(...ys)-1.2, yMax=Math.max(...ys)+1.4;
const PAD = 20, W = 430 - 2*PAD, H = 520 - 2*PAD;
sx = (x)=> PAD + (x-xMin)/(xMax-xMin)*W;
sy = (y)=> PAD + (yMax-y)/(yMax-yMin)*H;
}
// ==========================================
// 3. モードA ロジック (車格上限で自然切断)
// ==========================================
function runModeA() {
const CAPACITY = +document.getElementById('capSelectA').value;
// Gradツリー構築と容量チェック
const children = Array.from({length:n},()=>[]);
Object.entries(gradParent).forEach(([c,p])=>children[p].push(+c));
const inDeg = children.map(c=>c.length);
let stack = [...Array(n).keys()].filter(i=>inDeg[i]===0);
const order=[]; const done=new Array(n).fill(false);
while(stack.length){
const i = stack.pop();
if(done[i]) continue;
done[i]=true; order.push(i);
if(gradParent[i]!==undefined){ const p = gradParent[i]; inDeg[p]--; if(inDeg[p]===0) stack.push(p); }
}
const subtree = new Array(n).fill(0); const admitted = {}; const conflict = new Set();
for(const i of order){
const kids = children[i];
const totalAll = kids.reduce((a,c)=>a+subtree[c], RAW[i].demand);
if(kids.length===0){
subtree[i]=RAW[i].demand;
} else if(totalAll <= CAPACITY+1e-9){
kids.forEach(c=>admitted[c]=true);
subtree[i]=totalAll;
} else if(kids.length===1){
admitted[kids[0]]=false;
subtree[i]=RAW[i].demand;
} else {
kids.forEach(c=>{ admitted[c]=false; conflict.add(c); });
subtree[i]=RAW[i].demand;
}
}
const finalRoot = new Array(n);
for(let j=0;j<n;j++){ let cur=j; while(gradParent[cur]!==undefined && admitted[cur]===true){ cur = gradParent[cur]; } finalRoot[j]=cur; }
const clusters={};
for(let j=0;j<n;j++){ (clusters[finalRoot[j]] ??= []).push(j); }
// Map描画
drawSVG_ModeA(admitted, conflict, clusters, subtree);
// 表生成
let dispatchList = [];
let truckId = 1;
let unassigned = [];
Object.keys(clusters).forEach(r => {
let pts = clusters[r];
let loads = pts.filter(i => admitted[i] || +i === +r).map(i => ({
pName: RAW[i].name, area: RAW[i].near, load: RAW[i].demand, originalW: RAW[i].demand
}));
if(loads.length > 0) {
let total = loads.reduce((s,l)=>s+l.load, 0);
let size = [...CAR_CLASSES].sort((a,b)=>a-b).find(c => c >= total - 1e-9) || CAPACITY;
dispatchList.push({ id: truckId++, size: size, type: "自動クラスタ (谷)", loads: loads });
}
});
for(let i=0; i<n; i++){
if(conflict.has(i) || admitted[i]===false || saddleInfo[i]) {
unassigned.push({ pName: RAW[i].name, area: RAW[i].near, load: RAW[i].demand, originalW: RAW[i].demand, isErr: true });
}
}
if(unassigned.length > 0) {
dispatchList.push({ id: '⚠', size: '-', type: '上限超過/競合/尾根 による切断', isError: true, loads: unassigned });
}
renderRightTable(dispatchList);
document.getElementById('svgTitle').innerText = "地形トポロジー (上限による切断発生)";
}
// ==========================================
// 4. モードB ロジック (保有枠への強制詰め込み)
// ==========================================
let baseClustersB = {};
function runModeB_Ideal() {
// 一旦13t上限で自然なクラスタリングを算出し、目安を出す
const children = Array.from({length:n},()=>[]);
Object.entries(gradParent).forEach(([c,p])=>children[p].push(+c));
const inDeg = children.map(c=>c.length);
let stack = [...Array(n).keys()].filter(i=>inDeg[i]===0);
const order=[]; const done=new Array(n).fill(false);
while(stack.length){
const i = stack.pop(); if(done[i]) continue;
done[i]=true; order.push(i);
if(gradParent[i]!==undefined){ const p=gradParent[i]; inDeg[p]--; if(inDeg[p]===0) stack.push(p); }
}
const subtree = new Array(n).fill(0); const admitted = {};
for(const i of order){
const kids = children[i];
const totalAll = kids.reduce((a,c)=>a+subtree[c], RAW[i].demand);
if(kids.length===0){ subtree[i]=RAW[i].demand; }
else if(totalAll <= 13+1e-9){ kids.forEach(c=>admitted[c]=true); subtree[i]=totalAll; }
else { kids.forEach(c=>admitted[c]=false); subtree[i]=RAW[i].demand; }
}
const finalRoot = new Array(n);
for(let j=0;j<n;j++){ let cur=j; while(gradParent[cur]!==undefined && admitted[cur]===true){ cur = gradParent[cur]; } finalRoot[j]=cur; }
baseClustersB = {};
for(let j=0;j<n;j++){ (baseClustersB[finalRoot[j]] ??= []).push(j); }
// 台数見積もり
let ideal = {13:0, 10:0, 8:0, 6:0, 4:0, 2:0};
Object.values(baseClustersB).forEach(pts => {
let w = pts.reduce((s, i) => s + RAW[i].demand, 0);
ideal[13] += Math.floor(w/13);
let r = w % 13;
if(r > 0) { let s = CAR_CLASSES.find(x => x >= r) || 13; ideal[s] = (ideal[s]||0)+1; }
});
const row = document.getElementById('fleet-inputs-row');
row.innerHTML = '';
CAR_CLASSES.forEach(s => {
row.innerHTML += `<td><input type="number" id="input-fleet-${s}" value="${ideal[s]||0}" min="0"></td>`;
});
// マップは一旦グレーで地形のみ表示
drawSVG_ModeB([]);
document.getElementById('dispatchBody').innerHTML = '<tr><td colspan="4" class="center">保有枠を入力し、「配車を実行」を押してください</td></tr>';
document.getElementById('result-summary').innerHTML = '';
document.getElementById('svgTitle').innerText = "地形トポロジー (未割り当て)";
}
function runModeB_Execute() {
let pList = JSON.parse(JSON.stringify(RAW));
// 【Gradベースの空間的ソート】 谷底(ルート)ごとに、深い順に処理することで地理的近接性を保つ
let orderedIds = [];
Object.keys(baseClustersB).forEach(r => {
let pts = baseClustersB[r].sort((a,b) => height[a] - height[b]);
orderedIds.push(...pts);
});
// トラック準備
let availableTrucks = [];
let truckId = 1;
let totalCap = 0;
CAR_CLASSES.forEach(s => {
let c = parseInt(document.getElementById(`input-fleet-${s}`).value) || 0;
for(let i=0; i<c; i++) {
availableTrucks.push({ size: s, space: s, id: truckId++, type:"指示枠", loads: [] });
totalCap += s;
}
});
let totalLoad = RAW.reduce((s, p) => s + p.demand, 0);
if(totalCap < totalLoad) {
alert(`総積載能力(${totalCap}t)が荷物総量(${totalLoad.toFixed(1)}t)を下回っています。`);
return;
}
// Grad順序に従って貪欲パッキング(分割あり)
for(let id of orderedIds) {
let p = pList[id];
while(p.demand > 0.09) {
let t = availableTrucks.find(t => t.space >= p.demand) || availableTrucks.find(t => t.space > 0);
if(!t) break;
let take = Math.min(p.demand, t.space);
take = Math.floor(take * 10) / 10; // JS少数誤差対策
t.loads.push({ id: p.id, pName: p.name, area: p.near, load: take, originalW: RAW[p.id].demand });
t.space -= take;
p.demand -= take;
}
}
// カラ荷のトラックを除外
let usedTrucks = availableTrucks.filter(t => t.loads.length > 0);
renderRightTable(usedTrucks);
drawSVG_ModeB(usedTrucks);
document.getElementById('svgTitle').innerText = "地形トポロジー (車両割り当て結果)";
}
// ==========================================
// 5. 描画系 (SVG & テーブル)
// ==========================================
// SVG初期化&ラベル描画
function initSVG() {
const svg = document.getElementById('mapSvg'); svg.innerHTML = '';
const defs = el('defs',{});
const m = el('marker',{id:'arrow', markerWidth:6, markerHeight:6, refX:5, refY:3, orient:'auto'});
m.appendChild(el('path',{d:'M0,0 L6,3 L0,6 Z', fill: '#4A5C70'}));
defs.appendChild(m);
svg.appendChild(defs);
Object.entries(WARDS).forEach(([name,[x,y]])=>{
svg.appendChild(el('text',{x:sx(x),y:sy(y)-15,class:'ward-label','text-anchor':'middle'})).textContent=name;
});
return svg;
}
// モードA SVG描画
function drawSVG_ModeA(admitted, conflict, clusters, subtree) {
const svg = initSVG();
const rootsSorted = Object.keys(clusters).map(Number).sort((a,b)=>subtree[b]-subtree[a]);
const colorOf = {}; rootsSorted.forEach((r,i)=>colorOf[r]=PALETTE[i%PALETTE.length]);
// 接続線
for(let i=0; i<n; i++){
if(gradParent[i]===undefined) continue;
const p = gradParent[i], ok = admitted[i], conf = conflict.has(i);
const lineColor = ok ? '#8FA3B8' : (conf ? 'var(--conflict)' : 'var(--cut)');
svg.appendChild(el('line',{
x1:sx(RAW[i].x), y1:sy(RAW[i].y), x2:sx(RAW[p].x), y2:sy(RAW[p].y),
stroke: lineColor, 'stroke-width': ok?1:1.5, 'stroke-dasharray': ok?'none':'4,3', opacity: ok?0.5:0.8,
'marker-end': ok ? 'url(#arrow)' : ''
}));
}
// ノード
for(let i=0; i<n; i++){
const isConf = conflict.has(i), isRoot = isCritical.has(i);
let rootNode = i;
let curr = i; while(gradParent[curr]!==undefined && admitted[curr]){ curr = gradParent[curr]; rootNode = curr; }
const color = saddleInfo[i] ? 'var(--saddle)' : (isConf ? 'var(--conflict)' : (admitted[i]===false ? 'var(--cut)' : colorOf[rootNode]));
const r = (isRoot?1.2:1) * (4 + RAW[i].demand*3);
const c = el('circle',{cx:sx(RAW[i].x), cy:sy(RAW[i].y), r, fill:color, stroke: isRoot?'#fff':'#0B1420', 'stroke-width':isRoot?1.5:1});
c.addEventListener('mousemove', ev=>showTip(ev, `${RAW[i].near} / ${RAW[i].demand.toFixed(1)}t`));
c.addEventListener('mouseleave', hideTip);
svg.appendChild(c);
}
}
// モードB SVG描画 (パッキング結果に基づく色分け)
function drawSVG_ModeB(usedTrucks) {
const svg = initSVG();
// 各ノードがどのトラックに割り当てられたかマッピング
let nodeColors = {};
usedTrucks.forEach((t, i) => {
let color = PALETTE[i % PALETTE.length];
t.loads.forEach(l => { nodeColors[l.id] = color; }); // 分割時は最後に積まれたトラックの色になる
});
// 背景の地形接続線 (全ノード)
for(let i=0; i<n; i++){
if(gradParent[i]!==undefined) {
svg.appendChild(el('line',{
x1:sx(RAW[i].x), y1:sy(RAW[i].y), x2:sx(RAW[gradParent[i]].x), y2:sy(RAW[gradParent[i]].y),
stroke: '#4A5C70', 'stroke-width': 1, opacity: 0.4, 'marker-end': 'url(#arrow)'
}));
}
}
// ノード (トラックカラー)
for(let i=0; i<n; i++){
const isRoot = isCritical.has(i);
const r = (isRoot?1.2:1) * (4 + RAW[i].demand*3);
const color = nodeColors[i] || '#5B7189'; // 未割当はグレー
const c = el('circle',{cx:sx(RAW[i].x), cy:sy(RAW[i].y), r, fill:color, stroke: '#0B1420', 'stroke-width':1});
let tipText = `${RAW[i].near} / ${RAW[i].demand.toFixed(1)}t`;
c.addEventListener('mousemove', ev=>showTip(ev, tipText));
c.addEventListener('mouseleave', hideTip);
svg.appendChild(c);
}
}
// ツールチップ
const tooltip = document.getElementById('tooltip');
function showTip(ev, text){
tooltip.innerHTML = text;
const stage = document.getElementById('svgWrap').getBoundingClientRect();
tooltip.style.left = (ev.clientX - stage.left) + 'px';
tooltip.style.top = (ev.clientY - stage.top) + 'px';
tooltip.classList.add('show');
}
function hideTip(){ tooltip.classList.remove('show'); }
// 共通 右ペイン出力
function renderRightTable(dispatchList) {
const dBody = document.getElementById('dispatchBody');
const summaryDiv = document.getElementById('result-summary');
dBody.innerHTML = '';
if(dispatchList.length === 0) {
dBody.innerHTML = '<tr><td colspan="4" class="center">データがありません</td></tr>';
summaryDiv.innerHTML = '';
return;
}
// ===== サマリーの集計と描画 =====
let fleetCount = {};
let assignedLoad = 0;
dispatchList.forEach(truck => {
if (truck.isError) return; // 切断/エラー分は台数に含めない
fleetCount[truck.size] = (fleetCount[truck.size] || 0) + 1;
assignedLoad += truck.loads.reduce((s, item) => s + item.load, 0);
});
let summaryText = Object.keys(fleetCount)
.map(Number)
.sort((a,b) => b - a) // 車格の大きい順にソート
.map(size => `${size}t車:${fleetCount[size]}台`)
.join(' / ');
if (summaryText) {
summaryDiv.innerHTML = `<div class="summary-text">
<span style="color:#2980b9;">■ 手配内訳:</span> ${summaryText}
<div style="font-size:0.9em; font-weight:normal; color:#555; margin-top:4px;">
配車済みの荷物合計:${assignedLoad.toFixed(1)} t
</div>
</div>`;
} else {
summaryDiv.innerHTML = '';
}
// ==================================
dispatchList.forEach(truck => {
let totalLoad = truck.loads.reduce((s, item) => s + item.load, 0);
let headerClass = truck.isError ? "truck-header error" : "truck-header";
dBody.innerHTML += `
<tr class="${headerClass}">
<td colspan="4">🚚 ${truck.isError?'[警告]':'第 '+truck.id+' 便'} [ <span>${truck.size}t枠</span> ] (${truck.type})</td>
</tr>
<tr style="background:#f9f9f9; font-size: 0.9em;">
<th style="width:30%">品名</th><th style="width:25%">区</th><th style="width:20%">積載量</th><th style="width:25%">備考</th>
</tr>
`;
truck.loads.sort((a, b) => a.area.localeCompare(b.area)).forEach(item => {
let note = (item.load === item.originalW) ? "" : `<span class="split-note">※${item.originalW.toFixed(1)}tから分割</span>`;
if(item.isErr) note = `<span class="split-note">※切断/未定</span>`;
dBody.innerHTML += `
<tr>
<td class="product-name center">${item.pName}</td>
<td class="center">${item.area}</td>
<td class="num">${item.load.toFixed(1)} t</td>
<td class="center">${note}</td>
</tr>
`;
});
let spaceText = truck.size !== '-' ? `空き: ${(truck.size - totalLoad).toFixed(1)} t` : '';
dBody.innerHTML += `
<tr>
<td colspan="2" style="text-align:right; font-size: 0.9em;">積載合計:</td>
<td class="num" style="background:#fdf2e9; color:#d35400;">${totalLoad.toFixed(1)} t</td>
<td style="color:#7f8c8d; font-size: 0.85em;">${spaceText}</td>
</tr>
`;
});
}
// 初期化実行
switchMode();
</script>
</body>
</html>