Prompt specification
Build or customize the Three.js 3D scene "Linear and binary search comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Linear and binary search comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/linear-and-binary-search-comparison-x1850
Scene Description Prompt:
Compare stylized linear and binary searches on the same sorted list, including absent targets and examination counts. Three.js from cdnjs, one HTML file.
Working Three.js Starter (linear-and-binary-search-comparison-x1850):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Search Atlas — Linear vs Binary Search</title>
<style>
:root {
color-scheme: dark;
--bg: #050a12;
--panel: rgba(14, 24, 40, 0.88);
--panel-strong: rgba(18, 31, 51, 0.96);
--border: rgba(125, 166, 205, 0.18);
--text: #edf6ff;
--muted: #91a8be;
--blue: #38bdf8;
--cyan: #22d3ee;
--amber: #f59e0b;
--green: #22c55e;
--red: #ef4444;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
overflow-x: hidden;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 10% 0%, rgba(20, 104, 160, 0.22), transparent 34rem),
radial-gradient(circle at 100% 100%, rgba(14, 116, 144, 0.16), transparent 32rem),
var(--bg);
}
button,
input,
textarea {
font: inherit;
}
button {
cursor: pointer;
}
.app {
width: min(1560px, 100%);
margin: 0 auto;
padding: 18px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 14px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
position: relative;
width: 43px;
height: 43px;
flex: 0 0 auto;
border: 1px solid rgba(56, 189, 248, 0.4);
border-radius: 13px;
background:
linear-gradient(135deg, rgba(56, 189, 248, 0.24), rgba(34, 211, 238, 0.05));
box-shadow: 0 0 30px rgba(56, 189, 248, 0.12);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
left: 9px;
right: 9px;
height: 2px;
border-radius: 2px;
background: var(--blue);
transform-origin: left center;
}
.brand-mark::before {
top: 13px;
transform: rotate(28deg);
}
.brand-mark::after {
bottom: 13px;
background: var(--cyan);
transform: rotate(-28deg);
}
h1 {
margin: 0;
font-size: clamp(20px, 2.1vw, 30px);
letter-spacing: -0.035em;
line-height: 1.05;
}
.subtitle {
margin: 6px 0 0;
color: var(--muted);
font-size: 13px;
}
.header-note {
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
color: #b9cee0;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(12, 23, 39, 0.66);
font-size: 12px;
white-space: nowrap;
}
.header-note::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px rgba(34, 197, 94, 0.7);
}
.workspace {
display: grid;
grid-template-columns: 315px minmax(0, 1fr);
gap: 14px;
height: calc(100vh - 105px);
min-height: 650px;
}
.sidebar {
min-width: 0;
overflow: auto;
padding: 17px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.24);
scrollbar-width: thin;
scrollbar-color: #29415a transparent;
}
.section {
padding-bottom: 17px;
margin-bottom: 17px;
border-bottom: 1px solid var(--border);
}
.section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
color: #d9e9f7;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.075em;
text-transform: uppercase;
}
.mini-button {
padding: 5px 8px;
color: #b9d4e9;
border: 1px solid var(--border);
border-radius: 7px;
background: rgba(255, 255, 255, 0.035);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.mini-button:hover {
border-color: rgba(56, 189, 248, 0.4);
background: rgba(56, 189, 248, 0.08);
}
label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
textarea,
input[type="number"] {
width: 100%;
color: var(--text);
border: 1px solid rgba(125, 166, 205, 0.23);
outline: none;
background: rgba(4, 10, 18, 0.62);
transition: border-color 150ms, box-shadow 150ms;
}
textarea {
min-height: 88px;
padding: 11px;
resize: vertical;
border-radius: 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
}
input[type="number"] {
height: 42px;
padding: 0 11px;
border-radius: 10px;
font-size: 14px;
}
textarea:focus,
input[type="number"]:focus {
border-color: rgba(56, 189, 248, 0.7);
box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.09);
}
.field-help {
margin: 7px 0 0;
color: #6f879c;
font-size: 11px;
line-height: 1.45;
}
.target-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
align-items: center;
}
.target-chip {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 9px;
padding: 5px 8px;
border: 1px solid transparent;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
}
.target-chip.present {
color: #a7f3d0;
border-color: rgba(34, 197, 94, 0.22);
background: rgba(34, 197, 94, 0.08);
}
.target-chip.absent {
color: #fecaca;
border-color: rgba(239, 68, 68, 0.24);
background: rgba(239, 68, 68, 0.08);
}
.target-chip::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.button {
min-height: 39px;
padding: 8px 10px;
color: #d9eafa;
border: 1px solid rgba(125, 166, 205, 0.2);
border-radius: 9px;
background: rgba(255, 255, 255, 0.045);
font-size: 11px;
font-weight: 750;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.button:hover {
transform: translateY(-1px);
border-color: rgba(56, 189, 248, 0.4);
background: rgba(56, 189, 248, 0.08);
}
.button:active {
transform: translateY(0);
}
.button.primary {
color: #03131d;
border-color: transparent;
background: linear-gradient(135deg, #38bdf8, #22d3ee);
box-shadow: 0 8px 22px rgba(34, 211, 238, 0.14);
}
.button.primary:hover {
background: linear-gradient(135deg, #59c8ff, #36ddf4);
}
.button.full {
grid-column: 1 / -1;
}
.speed-row {
display: grid;
grid-template-columns: 1fr 58px;
gap: 10px;
align-items: center;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.speed-value {
padding: 6px 7px;
color: #c8e8f7;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(4, 10, 18, 0.45);
text-align: center;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.error {
min-height: 18px;
margin-top: 9px;
color: #fca5a5;
font-size: 11px;
line-height: 1.4;
}
.verdict {
padding: 13px;
border: 1px solid rgba(56, 189, 248, 0.16);
border-radius: 12px;
background:
radial-gradient(circle at 100% 0%, rgba(34, 211, 238, 0.1), transparent 60%),
rgba(6, 14, 25, 0.52);
}
.verdict-kicker {
color: #6f9bb8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.verdict h2 {
margin: 5px 0 7px;
font-size: 15px;
letter-spacing: -0.015em;
}
.verdict p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.count-pills {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 11px;
}
.count-pill {
padding: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.count-pill span {
display: block;
color: #7892a9;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.count-pill strong {
display: block;
margin-top: 2px;
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.stage {
position: relative;
min-width: 0;
min-height: 650px;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 18px;
background: #07111f;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.31);
isolation: isolate;
}
.stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
.stage canvas.dragging {
cursor: grabbing;
}
.stage::after {
content: "";
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
border-radius: inherit;
box-shadow: inset 0 0 80px rgba(0, 0, 0, 0.22);
}
.divider {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
z-index: 2;
width: 1px;
pointer-events: none;
background: linear-gradient(
transparent,
rgba(118, 161, 199, 0.2) 16%,
rgba(118, 161, 199, 0.2) 84%,
transparent
);
}
.stage.vertical .divider {
top: 50%;
right: 0;
bottom: auto;
left: 0;
width: auto;
height: 1px;
background: linear-gradient(
90deg,
transparent,
rgba(118, 161, 199, 0.2) 16%,
rgba(118, 161, 199, 0.2) 84%,
transparent
);
}
.hud {
position: absolute;
top: 18px;
left: 18px;
z-index: 3;
width: min(238px, calc(50% - 34px));
padding: 12px 13px;
pointer-events: none;
border: 1px solid rgba(125, 166, 205, 0.17);
border-radius: 12px;
background: rgba(5, 12, 22, 0.68);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.17);
backdrop-filter: blur(12px);
}
.hud.binary {
right: 18px;
left: auto;
}
.stage.vertical .hud {
right: auto;
left: 15px;
width: min(255px, calc(100% - 30px));
}
.stage.vertical .hud.binary {
top: auto;
right: auto;
bottom: 15px;
}
.algorithm-name {
display: flex;
align-items: center;
gap: 7px;
color: #8fb6cf;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.algorithm-name::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 10px rgba(245, 158, 11, 0.6);
}
.hud.binary .algorithm-name::before {
background: var(--cyan);
box-shadow: 0 0 10px rgba(34, 211, 238, 0.65);
}
.hud-number {
display: flex;
align-items: baseline;
gap: 8px;
margin-top: 4px;
}
.hud-number strong {
font-size: 31px;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.hud-number span {
color: #7893aa;
font-size: 10px;
}
.hud-status {
min-height: 15px;
margin-top: 6px;
overflow: hidden;
color: #a9bfd1;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.hud.complete .hud-status {
color: #b9f1d0;
}
.progress-track {
height: 3px;
margin-top: 8px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.055);
}
.progress-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--amber), #fbbf24);
transition: width 120ms linear;
}
.hud.binary .progress-fill {
background: linear-gradient(90deg, var(--cyan), #67e8f9);
}
.camera-help {
position: absolute;
bottom: 14px;
left: 50%;
z-index: 3;
padding: 7px 10px;
pointer-events: none;
color: #7690a5;
border: 1px solid rgba(125, 166, 205, 0.12);
border-radius: 999px;
background: rgba(5, 12, 22, 0.58);
font-size: 9px;
letter-spacing: 0.025em;
transform: translateX(-50%);
white-space: nowrap;
}
.stage.vertical .camera-help {
top: 50%;
bottom: auto;
transform: translate(-50%, -50%);
}
@media (max-width: 980px) {
.workspace {
grid-template-columns: 1fr;
height: auto;
}
.sidebar {
overflow: visible;
}
.stage {
height: 720px;
}
}
@media (max-width: 620px) {
.app {
padding: 10px;
}
.topbar {
align-items: flex-start;
}
.header-note {
display: none;
}
.workspace {
min-height: 0;
}
.sidebar {
padding: 14px;
border-radius: 14px;
}
.stage {
min-height: 700px;
height: 700px;
border-radius: 14px;
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<main class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Search Atlas</h1>
<p class="subtitle">A visual comparison of linear and binary search</p>
</div>
</div>
<div class="header-note">Same list. Same target. Different strategy.</div>
</header>
<div class="workspace">
<aside class="sidebar">
<section class="section">
<div class="section-title">
<span>Sorted list</span>
<button class="mini-button" id="sortButton" type="button">Sort</button>
</div>
<label for="listInput">Values, separated by commas</label>
<textarea id="listInput" spellcheck="false">2, 5, 8, 12, 16, 19, 23, 27, 31, 38, 41, 47</textarea>
<p class="field-help">
Use 2–18 unique values in strictly ascending order.
</p>
</section>
<section class="section">
<div class="section-title">Target</div>
<div class="target-row">
<input id="targetInput" type="number" value="23" step="any" />
</div>
<div id="targetMeta" class="target-chip present">Target is present</div>
<div class="button-grid">
<button id="presentButton" class="button" type="button">
Run present target
</button>
<button id="absentButton" class="button" type="button">
Run absent target
</button>
<button id="compareButton" class="button primary full" type="button">
Compare both searches
</button>
</div>
</section>
<section class="section">
<div class="section-title">Animation speed</div>
<div class="speed-row">
<input
id="speedInput"
type="range"
min="0.5"
max="3"
step="0.25"
value="1.25"
aria-label="Animation speed"
/>
<output id="speedValue" class="speed-value">1.25×</output>
</div>
</section>
<section class="section">
<div id="verdict" class="verdict">
<div class="verdict-kicker">Comparison</div>
<h2 id="verdictTitle">Ready to compare</h2>
<p id="verdictText">
Run the search to count every examined element, including a failed search.
</p>
<div class="count-pills">
<div class="count-pill">
<span>Linear</span>
<strong id="linearFinalCount">—</strong>
</div>
<div class="count-pill">
<span>Binary</span>
<strong id="binaryFinalCount">—</strong>
</div>
</div>
</div>
<div id="error" class="error" role="alert"></div>
</section>
</aside>
<section id="stage" class="stage" aria-label="Three-dimensional search comparison">
<div class="divider"></div>
<div class="hud linear" id="linearHud">
<div class="algorithm-name">Linear search</div>
<div class="hud-number">
<strong id="linearCount">0</strong>
<span>examinations</span>
</div>
<div id="linearStatus" class="hud-status">Ready to compare</div>
<div class="progress-track">
<div id="linearProgress" class="progress-fill"></div>
</div>
</div>
<div class="hud binary" id="binaryHud">
<div class="algorithm-name">Binary search</div>
<div class="hud-number">
<strong id="binaryCount">0</strong>
<span>examinations</span>
</div>
<div id="binaryStatus" class="hud-status">Ready to compare</div>
<div class="progress-track">
<div id="binaryProgress" class="progress-fill"></div>
</div>
</div>
<div class="camera-help">Drag to orbit · Scroll to zoom · Double-click to reset</div>
</section>
</div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const COLORS = {
idle: 0x1a496b,
idleEmissive: 0x061927,
idleEdge: 0x4d82a9,
current: 0xf59e0b,
currentEmissive: 0x7a3500,
currentEdge: 0xfbbf24,
visited: 0x9a5715,
visitedEmissive: 0x351706,
visitedEdge: 0xd38a2a,
found: 0x22c55e,
foundEmissive: 0x075a25,
foundEdge: 0x86efac,
absent: 0xef4444,
absentEmissive: 0x6f1010,
absentEdge: 0xfca5a5
};
const stage = document.getElementById("stage");
const listInput = document.getElementById("listInput");
const targetInput = document.getElementById("targetInput");
const targetMeta = document.getElementById("targetMeta");
const speedInput = document.getElementById("speedInput");
const speedValue = document.getElementById("speedValue");
const errorElement = document.getElementById("error");
const linearHud = document.getElementById("linearHud");
const binaryHud = document.getElementById("binaryHud");
const linearCount = document.getElementById("linearCount");
const binaryCount = document.getElementById("binaryCount");
const linearStatus = document.getElementById("linearStatus");
const binaryStatus = document.getElementById("binaryStatus");
const linearProgress = document.getElementById("linearProgress");
const binaryProgress = document.getElementById("binaryProgress");
const verdictTitle = document.getElementById("verdictTitle");
const verdictText = document.getElementById("verdictText");
const linearFinalCount = document.getElementById("linearFinalCount");
const binaryFinalCount = document.getElementById("binaryFinalCount");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D visualization. Drag to rotate and use the mouse wheel to zoom."
);
stage.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 150);
const cameraState = {
yaw: 0.13,
pitch: 0.43,
zoom: 1,
dragging: false,
pointerId: null,
lastX: 0,
lastY: 0
};
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeTextSprite(text, options = {}) {
const {
foreground = "#edf6ff",
background = "rgba(5, 13, 24, 0.9)",
border = "rgba(111, 167, 209, 0.5)",
scaleX = 1,
scaleY = 0.5,
fontSize = 64
} = options;
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 256, 128);
roundedRect(ctx, 7, 9, 242, 110, 22);
ctx.fillStyle = background;
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = border;
ctx.stroke();
ctx.fillStyle = foreground;
ctx.font = `700 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String(text), 128, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scaleX, scaleY, 1);
sprite.renderOrder = 10;
return sprite;
}
function disposeMaterial(material) {
if (!material) return;
if (Array.isArray(material)) {
material.forEach(disposeMaterial);
return;
}
if (material.map) material.map.dispose();
if (material.emissiveMap) material.emissiveMap.dispose();
material.dispose();
}
class SearchVisual {
constructor(algorithm) {
this.algorithm = algorithm;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x07111f);
this.items = [];
this.values = [];
this.rowWidth = 10;
this.currentIndex = null;
this.foundIndex = null;
this.dynamic = null;
this.createEnvironment();
}
createEnvironment() {
const hemisphere = new THREE.HemisphereLight(0xb9e8ff, 0x07101c, 2.1);
this.scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 3.2);
key.position.set(4, 10, 7);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -18;
key.shadow.camera.right = 18;
key.shadow.camera.top = 12;
key.shadow.camera.bottom = -12;
key.shadow.camera.near = 1;
key.shadow.camera.far = 50;
this.scene.add(key);
const rim = new THREE.PointLight(0x22d3ee, 18, 30, 2);
rim.position.set(-6, 5, -5);
this.scene.add(rim);
const warm = new THREE.PointLight(0xf59e0b, 11, 24, 2);
warm.position.set(6, 3, 3);
this.scene.add(warm);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(48, 38),
new THREE.MeshStandardMaterial({
color: 0x07111f,
roughness: 0.94,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.23;
floor.receiveShadow = true;
this.scene.add(floor);
const grid = new THREE.GridHelper(40, 40, 0x16496b, 0x0b293f);
grid.position.y = -0.215;
grid.material.transparent = true;
grid.material.opacity = 0.48;
this.scene.add(grid);
}
disposeDynamic() {
if (!this.dynamic) return;
this.dynamic.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) disposeMaterial(object.material);
});
this.scene.remove(this.dynamic);
}
build(values) {
this.disposeDynamic();
this.values = values;
this.currentIndex = null;
this.foundIndex = null;
const spacing = values.length > 14 ? 1.05 : 1.2;
this.spacing = spacing;
this.rowWidth = (values.length - 1) * spacing + 2.4;
this.dynamic = new THREE.Group();
this.scene.add(this.dynamic);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(this.rowWidth, 0.18, 3.25),
new THREE.MeshStandardMaterial({
color: 0x0b1c2d,
roughness: 0.64,
metalness: 0.22
})
);
platform.position.y = -0.11;
platform.receiveShadow = true;
this.dynamic.add(platform);
const lane = new THREE.Mesh(
new THREE.BoxGeometry(this.rowWidth - 0.9, 0.035, 0.065),
new THREE.MeshBasicMaterial({
color: this.algorithm === "linear" ? 0x8a5a16 : 0x167b95,
transparent: true,
opacity: 0.72
})
);
lane.position.set(0, 0.015, 0.28);
this.dynamic.add(lane);
const rangeMaterial = new THREE.MeshBasicMaterial({
color: 0x22d3ee,
transparent: true,
opacity: 0.82
});
this.rangeBar = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.045, 0.09),
rangeMaterial
);
this.rangeBar.position.y = 0.06;
this.rangeBar.position.z = 0.77;
this.rangeBar.visible = false;
this.dynamic.add(this.rangeBar);
this.rangeCapA = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 14, 10),
rangeMaterial
);
this.rangeCapB = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 14, 10),
rangeMaterial
);
this.rangeCapA.visible = false;
this.rangeCapB.visible = false;
this.dynamic.add(this.rangeCapA, this.rangeCapB);
this.items = values.map((value, index) => {
const x = (index - (values.length - 1) / 2) * spacing;
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(1.06, 0.22, 0.78),
new THREE.MeshStandardMaterial({
color: 0x102a40,
roughness: 0.68,
metalness: 0.26
})
);
pedestal.position.set(x, 0.09, 0);
pedestal.castShadow = true;
pedestal.receiveShadow = true;
this.dynamic.add(pedestal);
const cardMaterial = new THREE.MeshStandardMaterial({
color: COLORS.idle,
emissive: COLORS.idleEmissive,
emissiveIntensity: 0.45,
roughness: 0.34,
metalness: 0.18
});
const card = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.94, 0.49),
cardMaterial
);
card.position.set(x, 0.72, 0);
card.castShadow = true;
card.receiveShadow = true;
this.dynamic.add(card);
const edge = new THREE.LineSegments(
new THREE.EdgesGeometry(card.geometry),
new THREE.LineBasicMaterial({
color: COLORS.idleEdge,
transparent: true,
opacity: 0.9
})
);
edge.position.copy(card.position);
this.dynamic.add(edge);
const valueLabel = makeTextSprite(value, {
foreground: "#f1f8ff",
background: "rgba(5, 13, 24, 0.92)",
border: "rgba(91, 149, 193, 0.65)",
scaleX: 1.02,
scaleY: 0.51,
fontSize: value.toString().length > 5 ? 45 : 64
});
valueLabel.position.set(x, 1.48, 0.03);
this.dynamic.add(valueLabel);
const indexLabel = makeTextSprite(`i${index}`, {
foreground: "#6f9ab8",
background: "rgba(5, 13, 24, 0.58)",
border: "rgba(71, 119, 157, 0.28)",
scaleX: 0.48,
scaleY: 0.24,
fontSize: 46
});
indexLabel.position.set(x, 0.12, 0.58);
this.dynamic.add(indexLabel);
return {
index,
value,
x,
card,
edge,
valueLabel
};
});
this.probe = new THREE.Group();
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.32, 18),
new THREE.MeshBasicMaterial({ color: 0xf59e0b })
);
arrow.rotation.z = Math.PI;
arrow.position.y = 0.04;
this.probe.add(arrow);
const orb = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 16, 12),
new THREE.MeshBasicMaterial({ color: 0xfde68a })
);
orb.position.y = 0.31;
this.probe.add(orb);
this.probe.position.z = 0.68;
this.probe.visible = false;
this.dynamic.add(this.probe);
this.showIdle();
}
paintItem(item, color, emissive, intensity, edgeColor) {
item.card.material.color.setHex(color);
item.card.material.emissive.setHex(emissive);
item.card.material.emissiveIntensity = intensity;
item.edge.material.color.setHex(edgeColor);
}
showIdle() {
this.currentIndex = null;
this.foundIndex = null;
this.probe.visible = false;
this.rangeBar.visible = false;
this.rangeCapA.visible = false;
this.rangeCapB.visible = false;
this.items.forEach((item) => {
this.paintItem(
item,
COLORS.idle,
COLORS.idleEmissive,
0.45,
COLORS.idleEdge
);
});
}
setProgress(trace, count, result) {
const done = count >= trace.length;
this.items.forEach((item) => {
this.paintItem(
item,
COLORS.idle,
COLORS.idleEmissive,
0.45,
COLORS.idleEdge
);
});
for (let stepIndex = 0; stepIndex < count; stepIndex++) {
const step = trace[stepIndex];
const item = this.items[step.index];
const isCurrent = !done && stepIndex === count - 1;
if (done && result.found && step.index === result.index) {
this.paintItem(
item,
COLORS.found,
COLORS.foundEmissive,
0.72,
COLORS.foundEdge
);
this.foundIndex = step.index;
} else if (done && !result.found && stepIndex === count - 1) {
this.paintItem(
item,
COLORS.absent,
COLORS.absentEmissive,
0.66,
COLORS.absentEdge
);
} else if (isCurrent) {
this.paintItem(
item,
COLORS.current,
COLORS.currentEmissive,
0.66,
COLORS.currentEdge
);
} else {
this.paintItem(
item,
COLORS.visited,
COLORS.visitedEmissive,
0.4,
COLORS.visitedEdge
);
}
}
const currentStep = count > 0 ? trace[count - 1] : null;
this.currentIndex = currentStep ? currentStep.index : null;
if (this.algorithm === "binary" && currentStep && !done) {
const lo = this.items[currentStep.lo];
const hi = this.items[currentStep.hi];
const left = lo.x;
const right = hi.x;
this.rangeBar.visible = true;
this.rangeCapA.visible = true;
this.rangeCapB.visible = true;
this.rangeBar.position.x = (left + right) / 2;
this.rangeBar.scale.x = Math.max(0.12, right - left);
this.rangeCapA.position.set(left, 0.06, 0.77);
this.rangeCapB.position.set(right, 0.06, 0.77);
} else {
this.rangeBar.visible = false;
this.rangeCapA.visible = false;
this.rangeCapB.visible = false;
}
}
animate(time) {
this.items.forEach((item) => {
let scale = 1;
if (item.index === this.currentIndex) {
scale += Math.sin(time * 0.007) * 0.035;
} else if (item.index === this.foundIndex) {
scale = 1.065;
}
item.card.scale.set(scale, scale, scale);
});
if (this.currentIndex !== null && this.items[this.currentIndex]) {
this.probe.visible = true;
this.probe.position.x = this.items[this.currentIndex].x;
this.probe.position.y = 1.82 + Math.sin(time * 0.006) * 0.07;
} else {
this.probe.visible = false;
}
}
}
const linearVisual = new SearchVisual("linear");
const binaryVisual = new SearchVisual("binary");
function parseValues(text) {
const parts = text
.trim()
.split(/[\s,;]+/)
.filter(Boolean);
if (parts.length < 2) {
throw new Error("Enter at least two list values.");
}
if (parts.length > 18) {
throw new Error("Use no more than 18 values so the rows remain readable.");
}
const values = parts.map((part) => Number(part));
if (values.some((value) => !Number.isFinite(value))) {
throw new Error("Every list item must be a valid number.");
}
for (let i = 1; i < values.length; i++) {
if (values[i] <= values[i - 1]) {
throw new Error(
"The list must be strictly ascending with no duplicates. Use Sort if needed."
);
}
}
return values;
}
function parseTarget() {
const target = Number(targetInput.value);
if (!Number.isFinite(target)) {
throw new Error("Enter a valid numeric target.");
}
return target;
}
function makeLinearSearch(values, target) {
const trace = [];
let result = { found: false, index: -1 };
for (let index = 0; index < values.length; index++) {
trace.push({ index, lo: index, hi: index });
if (values[index] === target) {
result = { found: true, index };
break;
}
}
return { trace, result };
}
function makeBinarySearch(values, target) {
const trace = [];
let result = { found: false, index: -1 };
let lo = 0;
let hi = values.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
trace.push({ index: mid, lo, hi });
if (values[mid] === target) {
result = { found: true, index: mid };
break;
}
if (values[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return { trace, result };
}
let activeRun = null;
function setError(message = "") {
errorElement.textContent = message;
}
function updateTargetMeta() {
let values;
try {
values = parseValues(listInput.value);
} catch {
targetMeta.className = "target-chip absent";
targetMeta.textContent = "List needs attention";
return;
}
const target = Number(targetInput.value);
if (!Number.isFinite(target)) {
targetMeta.className = "target-chip absent";
targetMeta.textContent = "Enter a numeric target";
return;
}
const present = values.includes(target);
targetMeta.className = `target-chip ${present ? "present" : "absent"}`;
targetMeta.textContent = present ? "Target is present" : "Target is absent";
}
function resetReadout() {
linearCount.textContent = "0";
binaryCount.textContent = "0";
linearStatus.textContent = "Ready to compare";
binaryStatus.textContent = "Ready to compare";
linearProgress.style.width = "0%";
binaryProgress.style.width = "0%";
linearHud.classList.remove("complete");
binaryHud.classList.remove("complete");
linearFinalCount.textContent = "—";
binaryFinalCount.textContent = "—";
verdictTitle.textContent = "Ready to compare";
verdictText.textContent =
"Run the search to count every examined element, including a failed search.";
}
function startComparison(values = null, target = null) {
setError();
try {
const listValues = values || parseValues(listInput.value);
const searchTarget = target === null ? parseTarget() : target;
targetInput.value = String(searchTarget);
updateTargetMeta();
const linear = makeLinearSearch(listValues, searchTarget);
const binary = makeBinarySearch(listValues, searchTarget);
linearVisual.build(listValues);
binaryVisual.build(listValues);
resetReadout();
activeRun = {
values: listValues,
target: searchTarget,
linear,
binary,
start: performance.now() + 40,
interval: 650 / Number(speedInput.value),
lastLinear: -1,
lastBinary: -1,
verdictShown: false
};
} catch (error) {
setError(error.message);
}
}
function updateHud(algorithm, count, trace, result, values) {
const isLinear = algorithm === "linear";
const countElement = isLinear ? linearCount : binaryCount;
const statusElement = isLinear ? linearStatus : binaryStatus;
const progressElement = isLinear ? linearProgress : binaryProgress;
const hudElement = isLinear ? linearHud : binaryHud;
countElement.textContent = String(count);
if (count === 0) {
statusElement.textContent = "Ready to compare";
} else if (count < trace.length) {
const current = trace[count - 1].index;
statusElement.textContent = `Examining ${values[current]}`;
} else if (result.found) {
statusElement.textContent = `Found at position ${result.index + 1} of ${values.length}`;
} else {
statusElement.textContent = "Target not found";
}
progressElement.style.width = `${(count / trace.length) * 100}%`;
hudElement.classList.toggle("complete", count === trace.length);
}
function showFinalVerdict(linearCountValue, binaryCountValue, result) {
linearFinalCount.textContent = String(linearCountValue);
binaryFinalCount.textContent = String(binaryCountValue);
const difference = linearCountValue - binaryCountValue;
if (difference === 0) {
verdictTitle.textContent = "Equal examination count";
verdictText.textContent = result.found
? "Both strategies found the target after examining the same number of elements."
: "Both strategies searched the list without finding the target.";
} else if (difference > 0) {
const percent = Math.round((difference / linearCountValue) * 100);
verdictTitle.textContent = `Binary used ${difference} fewer examination${difference === 1 ? "" : "s"}`;
verdictText.textContent = `Binary searched ${percent}% fewer elements than linear search for this ${
result.found ? "present" : "absent"
} target.`;
} else {
const differenceReverse = Math.abs(difference);
verdictTitle.textContent = `Linear used ${differenceReverse} fewer examination${differenceReverse === 1 ? "" : "s"}`;
verdictText.textContent =
"For this particular target position, the linear search reached it with less work.";
}
}
function updateAnimation(time) {
if (!activeRun) return;
const elapsed = time - activeRun.start;
const getCount = (trace) => {
if (elapsed < 0) return 0;
return Math.min(trace.length, Math.floor(elapsed / activeRun.interval) + 1);
};
const linearSteps = getCount(activeRun.linear.trace);
const binarySteps = getCount(activeRun.binary.trace);
if (linearSteps !== activeRun.lastLinear) {
updateHud(
"linear",
linearSteps,
activeRun.linear.trace,
activeRun.linear.result,
activeRun.values
);
activeRun.lastLinear = linearSteps;
}
if (binarySteps !== activeRun.lastBinary) {
updateHud(
"binary",
binarySteps,
activeRun.binary.trace,
activeRun.binary.result,
activeRun.values
);
activeRun.lastBinary = binarySteps;
}
linearVisual.setProgress(
activeRun.linear.trace,
linearSteps,
activeRun.linear.result
);
binaryVisual.setProgress(
activeRun.binary.trace,
binarySteps,
activeRun.binary.result
);
const bothComplete =
linearSteps === activeRun.linear.trace.length &&
binarySteps === activeRun.binary.trace.length;
if (bothComplete && !activeRun.verdictShown) {
showFinalVerdict(
activeRun.linear.trace.length,
activeRun.binary.trace.length,
activeRun.linear.result
);
activeRun.verdictShown = true;
}
}
function updateCamera(aspect) {
camera.aspect = aspect;
camera.updateProjectionMatrix();
const halfFov = THREE.MathUtils.degToRad(camera.fov / 2);
const halfWidth = linearVisual.rowWidth / 2 + 1.1;
const halfHeight = 2.8;
const distanceForWidth = halfWidth / (Math.tan(halfFov) * aspect);
const distanceForHeight = halfHeight / Math.tan(halfFov);
const distance = Math.max(distanceForWidth, distanceForHeight, 8) * cameraState.zoom;
const target = new THREE.Vector3(0, 0.9, 0);
camera.position.set(
target.x + distance * Math.cos(cameraState.pitch) * Math.sin(cameraState.yaw),
target.y + distance * Math.sin(cameraState.pitch),
target.z + distance * Math.cos(cameraState.pitch) * Math.cos(cameraState.yaw)
);
camera.lookAt(target);
}
function renderScenes() {
const size = new THREE.Vector2();
renderer.getSize(size);
const width = Math.max(1, Math.floor(size.x));
const height = Math.max(1, Math.floor(size.y));
const vertical = stage.classList.contains("vertical");
renderer.setScissorTest(true);
if (vertical) {
const topHeight = Math.floor(height / 2);
const bottomHeight = height - topHeight;
renderer.setViewport(0, topHeight, width, topHeight);
renderer.setScissor(0, topHeight, width, topHeight);
updateCamera(width / topHeight);
renderer.render(linearVisual.scene, camera);
renderer.setViewport(0, 0, width, bottomHeight);
renderer.setScissor(0, 0, width, bottomHeight);
updateCamera(width / bottomHeight);
renderer.render(binaryVisual.scene, camera);
} else {
const leftWidth = Math.floor(width / 2);
const rightWidth = width - leftWidth;
renderer.setViewport(0, 0, leftWidth, height);
renderer.setScissor(0, 0, leftWidth, height);
updateCamera(leftWidth / height);
renderer.render(linearVisual.scene, camera);
renderer.setViewport(leftWidth, 0, rightWidth, height);
renderer.setScissor(leftWidth, 0, rightWidth, height);
updateCamera(rightWidth / height);
renderer.render(binaryVisual.scene, camera);
}
renderer.setScissorTest(false);
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
stage.classList.toggle("vertical", width < 720);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
function resetCamera() {
cameraState.yaw = 0.13;
cameraState.pitch = 0.43;
cameraState.zoom = 1;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.pointerId = event.pointerId;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!cameraState.dragging || event.pointerId !== cameraState.pointerId) {
return;
}
const dx = event.clientX - cameraState.lastX;
const dy = event.clientY - cameraState.lastY;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
cameraState.yaw = THREE.MathUtils.clamp(
cameraState.yaw - dx * 0.006,
-1.15,
1.15
);
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.16,
1.02
);
});
function endPointer(event) {
if (event.pointerId !== cameraState.pointerId) return;
cameraState.dragging = false;
cameraState.pointerId = null;
renderer.domElement.classList.remove("dragging");
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(event.deltaY * 0.001),
0.62,
1.9
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
const key = event.key;
if (key === "ArrowLeft") {
cameraState.yaw = THREE.MathUtils.clamp(cameraState.yaw + 0.08, -1.15, 1.15);
} else if (key === "ArrowRight") {
cameraState.yaw = THREE.MathUtils.clamp(cameraState.yaw - 0.08, -1.15, 1.15);
} else if (key === "ArrowUp") {
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + 0.06, 0.16, 1.02);
} else if (key === "ArrowDown") {
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch - 0.06, 0.16, 1.02);
} else if (key === "+" || key === "=") {
cameraState.zoom = THREE.MathUtils.clamp(cameraState.zoom * 0.92, 0.62, 1.9);
} else if (key === "-") {
cameraState.zoom = THREE.MathUtils.clamp(cameraState.zoom * 1.08, 0.62, 1.9);
} else if (key === "Escape") {
resetCamera();
} else {
return;
}
event.preventDefault();
});
document.getElementById("compareButton").addEventListener("click", () => {
startComparison();
});
document.getElementById("sortButton").addEventListener("click", () => {
try {
const parts = listInput.value
.trim()
.split(/[\s,;]+/)
.filter(Boolean)
.map(Number);
if (parts.some((value) => !Number.isFinite(value))) {
throw new Error("Every list item must be a valid number.");
}
parts.sort((a, b) => a - b);
listInput.value = parts.join(", ");
setError();
updateTargetMeta();
} catch (error) {
setError(error.message);
}
});
document.getElementById("presentButton").addEventListener("click", () => {
try {
const values = parseValues(listInput.value);
const target = values[Math.floor(values.length / 2)];
startComparison(values, target);
} catch (error) {
setError(error.message);
}
});
document.getElementById("absentButton").addEventListener("click", () => {
try {
const values = parseValues(listInput.value);
let target = values[0] - 1;
for (let i = 1; i < values.length; i++) {
if (values[i] - values[i - 1] > 1) {
target = (values[i] + values[i - 1]) / 2;
break;
}
}
if (values.includes(target)) {
target = values[values.length - 1] + 1;
}
startComparison(values, target);
} catch (error) {
setError(error.message);
}
});
speedInput.addEventListener("input", () => {
const speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(2).replace(/0$/, "")}×`;
if (activeRun) {
activeRun.interval = 650 / speed;
}
});
listInput.addEventListener("input", () => {
setError();
updateTargetMeta();
});
targetInput.addEventListener("input", updateTargetMeta);
function animate(time) {
requestAnimationFrame(animate);
updateAnimation(time);
linearVisual.animate(time);
binaryVisual.animate(time);
renderScenes();
}
const initialValues = parseValues(listInput.value);
linearVisual.build(initialValues);
binaryVisual.build(initialValues);
updateTargetMeta();
resize();
requestAnimationFrame(animate);
</script>
</body>
</html>
```