Repository navigation
Expand file tree
/
Copy pathCollatz reverse tree.html
More file actions
754 lines (706 loc) · 29.6 KB
/
Copy pathCollatz reverse tree.html
File metadata and controls
754 lines (706 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Collatz Reverse Tree – Interactive Visualizer with (m,k) toggle & PNG export</title>
<meta name="description" content="Explore the cycle-pruned reverse Collatz tree in your browser: adjust depth, click any node to trace its forward trajectory to 1, switch between integer and (m,k) coordinates, and export the fitted view as PNG.">
<link rel="canonical" href="https://keng0nion.github.io/Collatz-Conjecture-Reverse-Tree-Interactive-Visualizer/Collatz%20reverse%20tree.html">
<meta property="og:type" content="website">
<meta property="og:title" content="Collatz Reverse Tree – Interactive Visualizer with (m,k) toggle & PNG export">
<meta property="og:description" content="Explore the cycle-pruned reverse Collatz tree in your browser: adjust depth, click any node to trace its forward trajectory to 1, switch between integer and (m,k) coordinates, and export the fitted view as PNG.">
<meta property="og:url" content="https://keng0nion.github.io/Collatz-Conjecture-Reverse-Tree-Interactive-Visualizer/Collatz%20reverse%20tree.html">
<meta property="og:image" content="https://keng0nion.github.io/Collatz-Conjecture-Reverse-Tree-Interactive-Visualizer/docs/screenshot.png">
<meta name="twitter:card" content="summary_large_image">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebApplication",
"name": "Collatz Reverse Tree Visualizer",
"url": "https://keng0nion.github.io/Collatz-Conjecture-Reverse-Tree-Interactive-Visualizer/Collatz%20reverse%20tree.html",
"description": "An interactive browser visualizer for the cycle-pruned reverse Collatz tree, with adjustable depth, forward-trajectory highlighting, (m,k) coordinate labels, and PNG export.",
"applicationCategory": "EducationalApplication",
"isAccessibleForFree": true,
"inLanguage": "en"
}
</script>
<!-- vis-network core library -->
<script type="text/javascript" src="https://unpkg.com/vis-network@9.1.6/dist/vis-network.min.js"></script>
<script type="text/javascript" src="collatz-math.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background: #f5f7fb;
color: #1a2a3a;
}
.container {
display: flex;
flex-direction: column;
height: 100vh;
width: 100%;
}
.toolbar {
background: white;
padding: 12px 20px;
border-bottom: 1px solid #dce4ec;
box-shadow: 0 2px 6px rgba(0,0,0,0.05);
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
z-index: 10;
}
.control-group {
display: flex;
align-items: center;
gap: 12px;
background: #f8fafc;
padding: 5px 15px;
border-radius: 40px;
border: 1px solid #e2e8f0;
}
.control-group label {
font-weight: 600;
font-size: 0.9rem;
}
input[type="number"] {
width: 110px;
padding: 6px 10px;
font-size: 1rem;
border-radius: 30px;
border: 1px solid #cbd5e1;
text-align: center;
font-weight: bold;
background: white;
}
button {
background: #2c3e66;
border: none;
color: white;
padding: 6px 22px;
border-radius: 30px;
font-weight: 600;
cursor: pointer;
transition: 0.2s;
font-size: 0.85rem;
border: 1px solid #1e2a44;
display: inline-flex;
align-items: center;
gap: 6px;
}
button:hover {
background: #1e2a44;
transform: scale(0.98);
}
.export-btn {
background: #2b6e4f;
border-color: #1e4a37;
}
.export-btn:hover {
background: #1e4a37;
}
.toggle-btn {
background: #6c5b7b;
border-color: #4b3a5e;
}
.toggle-btn:hover {
background: #4b3a5e;
}
.info-panel {
background: #fff9f0;
border-left: 4px solid #f39c12;
padding: 8px 16px;
font-size: 0.85rem;
border-radius: 12px;
max-width: 380px;
box-shadow: 0 1px 4px rgba(0,0,0,0.05);
flex-shrink: 1;
}
.info-panel h1 {
display: inline;
margin: 0;
font-size: 1em;
font-weight: 700;
color: #e67e22;
}
.info-panel strong {
color: #e67e22;
}
.stats {
font-family: monospace;
font-size: 0.8rem;
background: #eef2f7;
padding: 5px 12px;
border-radius: 20px;
white-space: nowrap;
}
.graph-container {
flex: 1;
position: relative;
background: #ffffff;
overflow: hidden;
}
#network {
width: 100%;
height: 100%;
background: #ffffff;
}
.legend {
position: absolute;
bottom: 15px;
right: 15px;
background: rgba(255,255,255,0.94);
backdrop-filter: blur(5px);
border-radius: 14px;
padding: 10px 16px;
font-size: 0.7rem;
border: 1px solid #ccc;
pointer-events: none;
z-index: 20;
font-family: 'Segoe UI', monospace;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
line-height: 1.5;
max-width: 280px;
}
.legend span {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 50%;
margin-right: 6px;
vertical-align: middle;
}
.legend .mk-desc {
font-size: 0.65rem;
color: #2c3e66;
border-top: 1px solid #e2e8f0;
margin-top: 6px;
padding-top: 5px;
font-family: monospace;
}
.status-msg {
font-size: 0.8rem;
color: #2c6e2c;
margin-left: 10px;
background: #ecfdf5;
padding: 4px 10px;
border-radius: 20px;
}
.warning {
color: #e67e22;
font-weight: 500;
}
@media (max-width: 860px) {
.toolbar { flex-direction: column; align-items: stretch; gap: 10px; }
.control-group { justify-content: space-between; }
.info-panel { max-width: 100%; }
.stats { text-align: center; }
.legend { font-size: 0.6rem; max-width: 260px; padding: 8px 12px; }
}
.footer {
font-size: 0.7rem;
text-align: center;
background: #f0f2f5;
padding: 4px;
}
button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
</style>
</head>
<body>
<div class="container">
<div class="toolbar">
<div class="control-group">
<label>🔢 Max steps (depth):</label>
<input type="number" id="stepInput" min="1" max="30" value="4" step="1" style="width: 100px;">
<button id="generateBtn">⟳ Generate / Refresh Tree</button>
</div>
<button id="toggleDisplayBtn" class="toggle-btn">🔄 Toggle (m,k) Coordinates</button>
<button id="exportPngBtn" class="export-btn">📸 Export PNG (Fitted View)</button>
<div class="info-panel" id="infoPanel">
📘 <h1>Cycle-pruned Collatz Reverse Tree</h1> · growing backwards from 1<br>
🟢 Click any node to show its forward trajectory to 1 · Switch to (m,k) mode
</div>
<div class="stats" id="statsArea">
Nodes: — | Edges: —
</div>
<div id="statusMsg" class="status-msg">✅ Ready</div>
</div>
<div class="graph-container">
<div id="network"></div>
<div class="legend">
<div><span style="background: #3b82f6;"></span> Step 0 (root 1)</div>
<div><span style="background: #f97316;"></span> Step ≥4</div>
<div><span style="background: #a78bfa;"></span> Intermediate steps</div>
<div>🖱️ Scroll zoom · Drag pan · Click node</div>
<div>📸 Export PNG · 🔄 Coordinate mode</div>
<div class="mk-desc">
<strong>(m,k) conversion</strong><br>
m = ⌊n/6⌋ k = n mod 6<br>
→ displayed as (m, k)
</div>
</div>
</div>
<div class="footer">
💡 Reverse rules: predecessors are 2x and (x−1)/3 when the latter is a positive odd integer. The edge 4 → 1 is omitted to break the 1–4–2 cycle. | <span class="warning">⚠️ Depth 27 produces 1,748 nodes in this implementation; deeper trees may render slowly. PNG export captures the fitted viewport. | (m,k): m = floor(n/6), k = n mod 6</span>
</div>
</div>
<script>
// --------------------------------------------------------------
// Collatz reverse tree generator (BFS)
// Returns { nodes, edges, parentMap, stepsMap }
// --------------------------------------------------------------
function generateCollatzTree(maxSteps) {
const { stepsMap, parentMap } = CollatzMath.generateReverseTree(1, maxSteps, {
pruneRootCycle: true
});
let nodes = [];
let edges = [];
let nodeSet = new Set();
for (let [nodeId, step] of stepsMap.entries()) {
if (step <= maxSteps) {
nodeSet.add(nodeId);
}
}
for (let [child, parent] of parentMap.entries()) {
if (parent !== null && nodeSet.has(child) && nodeSet.has(parent)) {
if (stepsMap.get(child) <= maxSteps && stepsMap.get(parent) <= maxSteps) {
edges.push({ id: `${parent}->${child}`, from: parent, to: child });
}
}
}
for (let nodeId of nodeSet) {
let step = stepsMap.get(nodeId);
let hue = 0.55 - (step / (maxSteps + 0.5)) * 0.45;
let saturation = 0.7;
let lightness = 0.55 + (step / (maxSteps + 1)) * 0.2;
let color = `hsl(${hue * 360}, ${saturation * 100}%, ${lightness * 100}%)`;
let size = 22 + Math.max(0, (maxSteps - step) * 1.2);
size = Math.min(34, size);
nodes.push({
id: nodeId,
label: nodeId.toString(),
title: `Number: ${nodeId}\nStep: ${step}\n(distance from 1)`,
step: step,
color: color,
size: size,
font: { size: 12, color: '#1e293b' }
});
}
nodes.sort((a,b) => a.step - b.step);
return { nodes: nodes, edges: edges, parentMap: parentMap, stepsMap: stepsMap };
}
// ---------- Helper: format number as (m,k) ----------
function formatNumberToMK(n) {
const { m, k } = CollatzMath.toMK(n);
return `(${m},${k})`;
}
// Global variables
let network = null;
let currentParentMap = null;
let currentStepsMap = null;
let currentMaxSteps = 4;
let currentNodesDataSet = null;
let currentDisplayMode = 'number'; // 'number' or 'mk'
let isExporting = false;
// --------------------------------------------------------------
// Refresh node labels according to currentDisplayMode
// --------------------------------------------------------------
function refreshLabelsByMode() {
if (!currentNodesDataSet) {
console.warn("No nodesDataSet, cannot refresh labels");
return false;
}
try {
const nodesArray = currentNodesDataSet.get();
if (!nodesArray || nodesArray.length === 0) return false;
const updates = [];
for (let node of nodesArray) {
const originalNumber = node.id;
let newLabel = '';
if (currentDisplayMode === 'number') {
newLabel = originalNumber.toString();
} else {
newLabel = formatNumberToMK(originalNumber);
}
if (node.label !== newLabel) {
updates.push({ id: node.id, label: newLabel });
}
}
if (updates.length > 0) {
currentNodesDataSet.update(updates);
}
return true;
} catch (err) {
console.error("Failed to refresh labels:", err);
return false;
}
}
// --------------------------------------------------------------
// Toggle display mode
// --------------------------------------------------------------
function toggleDisplayMode() {
if (!network || !currentNodesDataSet) {
showStatusMessage("❌ Tree not loaded, please generate first", true);
return;
}
const toggleBtn = document.getElementById('toggleDisplayBtn');
if (currentDisplayMode === 'number') {
currentDisplayMode = 'mk';
if (toggleBtn) toggleBtn.innerHTML = '🔢 Show Numbers';
showStatusMessage("Switched to (m,k) coordinate display", false);
} else {
currentDisplayMode = 'number';
if (toggleBtn) toggleBtn.innerHTML = '🔄 Toggle (m,k) Coordinates';
showStatusMessage("Restored raw number display", false);
}
const success = refreshLabelsByMode();
if (!success) {
showStatusMessage("⚠️ Label refresh failed, please regenerate tree", true);
}
setTimeout(() => {
if (network) network.fit({ animation: true, duration: 200 });
}, 50);
}
// --------------------------------------------------------------
// Merge vis-network canvases to a single data URL
// --------------------------------------------------------------
function mergeCanvasesToDataURL(containerElement) {
return new Promise((resolve, reject) => {
try {
const canvases = containerElement.querySelectorAll('canvas');
if (!canvases || canvases.length === 0) {
reject(new Error("No canvases found, please try again"));
return;
}
const refCanvas = canvases[0];
const width = refCanvas.width;
const height = refCanvas.height;
if (width === 0 || height === 0) {
reject(new Error("Canvas has zero size, cannot export"));
return;
}
const mergedCanvas = document.createElement('canvas');
mergedCanvas.width = width;
mergedCanvas.height = height;
const ctx = mergedCanvas.getContext('2d');
if (!ctx) {
reject(new Error("Cannot get canvas context"));
return;
}
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, width, height);
canvases.forEach(canvas => {
if (canvas.width > 0 && canvas.height > 0) {
try {
ctx.drawImage(canvas, 0, 0, width, height);
} catch (err) {
console.warn("Failed to draw a layer:", err);
}
}
});
const dataURL = mergedCanvas.toDataURL('image/png');
resolve(dataURL);
} catch (err) {
reject(err);
}
});
}
// --------------------------------------------------------------
// Export current view as PNG
// --------------------------------------------------------------
async function exportAsPNG() {
if (!network) {
showStatusMessage("❌ Network not initialised, generate tree first", true);
return;
}
if (isExporting) {
showStatusMessage("⏳ Export already in progress, please wait...");
return;
}
const container = document.getElementById('network');
if (!container) return;
const statsText = document.getElementById('statsArea').innerText;
const nodeMatch = statsText.match(/Nodes:\s*(\d+)/);
let nodeCount = 0;
if (nodeMatch && nodeMatch[1]) nodeCount = parseInt(nodeMatch[1], 10);
if (nodeCount > 1200) {
const confirmExport = confirm(`Current tree has ${nodeCount} nodes. Exporting may take a few seconds and produce a large image. Continue?`);
if (!confirmExport) return;
}
isExporting = true;
const exportBtn = document.getElementById('exportPngBtn');
const originalBtnText = exportBtn.innerHTML;
exportBtn.innerHTML = "⏳ Capturing...";
exportBtn.disabled = true;
showStatusMessage("📸 Fitting full tree and rendering snapshot...");
try {
network.selectNodes([]);
network.fit({ animation: false, scale: 1.0 });
await new Promise(resolve => setTimeout(resolve, 280));
await new Promise(requestAnimationFrame);
await new Promise(resolve => setTimeout(resolve, 60));
const dataURL = await mergeCanvasesToDataURL(container);
const timestamp = new Date().toISOString().slice(0,19).replace(/:/g, '-');
const modeSuffix = currentDisplayMode === 'mk' ? '_MK' : '_NUM';
const filename = `Collatz_tree_depth${currentMaxSteps}${modeSuffix}_${timestamp}.png`;
const link = document.createElement('a');
link.download = filename;
link.href = dataURL;
link.click();
showStatusMessage(`✅ Exported successfully: ${filename} (${nodeCount} nodes)`, false);
} catch (err) {
console.error("Export failed:", err);
showStatusMessage(`❌ Export failed: ${err.message}`, true);
} finally {
isExporting = false;
exportBtn.innerHTML = originalBtnText;
exportBtn.disabled = false;
setTimeout(() => {
if (!isExporting) showStatusMessage("✅ Export complete, you can now pan/zoom", false);
}, 1500);
}
}
// Helper: show status message
let statusTimeout = null;
function showStatusMessage(msg, isError = false) {
const statusDiv = document.getElementById('statusMsg');
if (!statusDiv) return;
if (statusTimeout) clearTimeout(statusTimeout);
statusDiv.innerHTML = isError ? `⚠️ ${msg}` : `✨ ${msg}`;
if (isError) {
statusTimeout = setTimeout(() => {
if (statusDiv.innerHTML.includes(msg)) {
statusDiv.innerHTML = "✅ Ready";
}
}, 3000);
} else {
statusTimeout = setTimeout(() => {
if (statusDiv.innerHTML === `✨ ${msg}` || statusDiv.innerHTML === `✅ ${msg}`) {
statusDiv.innerHTML = "✅ Ready";
}
}, 2500);
}
}
// --------------------------------------------------------------
// Render the network graph
// --------------------------------------------------------------
function renderTree(maxSteps) {
const container = document.getElementById('network');
if (!container) return;
const statusMsgDiv = document.getElementById('statusMsg');
const statsArea = document.getElementById('statsArea');
statusMsgDiv.innerHTML = '⏳ Generating tree... (may take a while for large depths)';
statsArea.innerHTML = 'Nodes: — | Edges: —';
setTimeout(() => {
try {
const { nodes, edges, parentMap, stepsMap } = generateCollatzTree(maxSteps);
currentParentMap = parentMap;
currentStepsMap = stepsMap;
currentMaxSteps = maxSteps;
const nodeCount = nodes.length;
const edgeCount = edges.length;
statsArea.innerHTML = `📊 Nodes: ${nodeCount} | Edges: ${edgeCount}`;
statusMsgDiv.innerHTML = `✅ Tree generated (depth ${maxSteps}, ${nodeCount} nodes)`;
if (nodeCount === 0) {
statusMsgDiv.innerHTML = '⚠️ No nodes generated, increase depth';
return;
}
if (nodeCount > 1200) {
statusMsgDiv.innerHTML = '⚠️ Many nodes (>1200), interaction may be sluggish, consider reducing depth';
}
// Set initial labels according to current mode
for (let node of nodes) {
if (currentDisplayMode === 'mk') {
node.label = formatNumberToMK(node.id);
} else {
node.label = node.id.toString();
}
}
const nodesDataSet = new vis.DataSet(nodes);
const edgesDataSet = new vis.DataSet(edges);
currentNodesDataSet = nodesDataSet;
const options = {
autoResize: true,
height: '100%',
width: '100%',
layout: {
hierarchical: {
enabled: true,
direction: 'UD',
sortMethod: 'directed',
nodeSpacing: 130,
levelSeparation: 150,
parentCentralization: true
}
},
physics: { enabled: false, stabilization: false },
interaction: {
hover: true,
tooltipDelay: 200,
zoomView: true,
dragView: true,
navigationButtons: false,
keyboard: true
},
nodes: {
shape: 'dot',
scaling: { label: { enabled: true }, min: 16, max: 32 },
font: { size: 11, face: 'monospace', background: 'rgba(255,255,240,0.8)', strokeWidth: 0 },
borderWidth: 1,
borderWidthSelected: 2,
shadow: false
},
edges: {
arrows: { to: { enabled: true, scaleFactor: 0.8 } },
color: { color: '#94a3b8', highlight: '#f97316', opacity: 0.6 },
smooth: { type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.3 },
width: 1.5
}
};
if (network !== null) {
network.destroy();
network = null;
}
network = new vis.Network(container, { nodes: nodesDataSet, edges: edgesDataSet }, options);
network.once('layoutStabilized', function() {
network.fit({ animation: true, duration: 300 });
});
setTimeout(() => {
if (network) network.fit({ animation: true });
}, 200);
network.on("click", function(params) {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
showNodePath(nodeId);
}
});
} catch (err) {
console.error(err);
statusMsgDiv.innerHTML = '❌ Generation failed: ' + err.message;
}
}, 20);
}
// --------------------------------------------------------------
// Show the forward Collatz trajectory from the selected node to root 1
// --------------------------------------------------------------
function showNodePath(nodeId) {
if (!currentParentMap || !currentStepsMap) {
showStatusMessage("Tree data not ready, please try again", true);
return;
}
if (!currentParentMap.has(nodeId) && nodeId !== 1) {
showStatusMessage(`Node ${nodeId} does not exist in the current tree`, true);
return;
}
let path = [];
let cur = nodeId;
while (cur !== null && cur !== undefined) {
path.push(cur);
cur = currentParentMap.get(cur);
if (cur === null) break;
}
const stepCount = currentStepsMap.get(nodeId) || (path.length - 1);
let pathStr = path.join(" → ");
const isLong = pathStr.length > 260;
if (isLong) {
pathStr = pathStr.slice(0, 240) + "… → 1";
}
const infoDiv = document.getElementById('infoPanel');
if (infoDiv) {
infoDiv.innerHTML = `🔍 <strong>Forward Collatz trajectory</strong> · ${nodeId} to 1<br>
📌 Steps: ${stepCount}<br>
🧩 Trajectory: ${pathStr}<br>
<span style="font-size:0.7rem;">✨ Rule: odd → 3x+1, even → x/2</span>
<br><span style="font-size:0.65rem; color:#8b5a2b;">💡 Graph arrows show reverse expansion; this trajectory follows them back toward the root.</span>`;
if (network) {
const pathEdges = [];
for (let index = 0; index < path.length - 1; index += 1) {
pathEdges.push(`${path[index + 1]}->${path[index]}`);
}
network.setSelection(
{ nodes: path, edges: pathEdges },
{ unselectAll: true, highlightEdges: false }
);
setTimeout(() => { if (network) network.unselectAll(); }, 2400);
}
} else {
alert(`Forward Collatz trajectory ${nodeId} → 1 (${stepCount} steps):\n${pathStr}`);
}
showStatusMessage(`Displayed forward trajectory for node ${nodeId}`, false);
}
// --------------------------------------------------------------
// UI initialisation
// --------------------------------------------------------------
function initUI() {
const stepInput = document.getElementById('stepInput');
const generateBtn = document.getElementById('generateBtn');
const exportBtn = document.getElementById('exportPngBtn');
const toggleBtn = document.getElementById('toggleDisplayBtn');
generateBtn.addEventListener('click', function() {
if (isExporting) {
showStatusMessage("Export in progress, please wait before generating", true);
return;
}
let rawValue = stepInput.value.trim();
let maxSteps = parseInt(rawValue, 10);
if (isNaN(maxSteps) || maxSteps < 1) {
showStatusMessage('Please enter a valid step count (≥1)', true);
return;
}
if (maxSteps > 30) {
showStatusMessage('Please enter a depth from 1 to 30; larger depths are disabled to keep integer arithmetic and rendering manageable', true);
return;
}
if (maxSteps >= 27) {
if (!confirm(`Depth 27 produces 1,748 nodes, and deeper values grow quickly. Rendering and export may be slow. Continue with depth ${maxSteps}?`)) {
return;
}
}
// Keep the current display mode preference
if (currentDisplayMode === 'mk') {
if (toggleBtn) toggleBtn.innerHTML = '🔢 Show Numbers';
} else {
if (toggleBtn) toggleBtn.innerHTML = '🔄 Toggle (m,k) Coordinates';
}
renderTree(maxSteps);
});
toggleBtn.addEventListener('click', () => {
if (!network || !currentNodesDataSet) {
showStatusMessage("Please generate a tree first", true);
return;
}
toggleDisplayMode();
});
exportBtn.addEventListener('click', () => {
if (!network) {
showStatusMessage("❌ Please generate a tree first", true);
return;
}
exportAsPNG();
});
// Initial render with depth 4
currentDisplayMode = 'number';
if (toggleBtn) toggleBtn.innerHTML = '🔄 Toggle (m,k) Coordinates';
renderTree(4);
stepInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
generateBtn.click();
}
});
window.addEventListener('resize', () => {
if (network) network.fit();
});
}
window.addEventListener('DOMContentLoaded', initUI);
</script>
</body>
</html>