-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
428 lines (360 loc) · 14.2 KB
/
script.js
File metadata and controls
428 lines (360 loc) · 14.2 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
/**
* Binary Search Visualizer — script.js
*
* Flow:
* 1. User types their own numbers (or clicks Random).
* 2. "Build & Sort" animates a Bubble Sort so they see how sorting works.
* 3. After sorting, clickable chips appear for every value in the array.
* 4. User either types a target OR clicks a chip → animated Binary Search runs.
*/
// ── State ────────────────────────────────────────────────────
let array = []; // the working (sorted) array
let isRunning = false; // true while any animation is playing
let stopFlag = false; // set true on Reset to abort animations
// ── Speed map (slider 1–5 → delay ms) ──────────────────────
const speedMap = { 1: 1200, 2: 750, 3: 420, 4: 200, 5: 80 };
// ── DOM ──────────────────────────────────────────────────────
const arrayInput = document.getElementById('arrayInput');
const buildBtn = document.getElementById('buildBtn');
const randomBtn = document.getElementById('randomBtn');
const targetInput = document.getElementById('targetInput');
const searchBtn = document.getElementById('searchBtn');
const resetBtn = document.getElementById('resetBtn');
const speedSlider = document.getElementById('speedSlider');
const arrayContainer = document.getElementById('arrayContainer');
const pointerRow = document.getElementById('pointerRow');
const statusBar = document.getElementById('statusBar');
const statusMsg = document.getElementById('statusMsg');
const stepCountEl = document.getElementById('stepCount');
const arrayHint = document.getElementById('arrayHint');
const emptyState = document.getElementById('emptyState');
const chipsSection = document.getElementById('chipsSection');
const chipsRow = document.getElementById('chipsRow');
// ── Utility ──────────────────────────────────────────────────
/** Cancellable delay. Rejects with 'stopped' if stopFlag is set. */
function delay(ms) {
return new Promise((resolve, reject) => {
if (stopFlag) { reject('stopped'); return; }
const id = setTimeout(() => stopFlag ? reject('stopped') : resolve(), ms);
window._animId = id;
});
}
/** Set status bar state + message. */
function setStatus(state, msg) {
statusBar.className = 'status-bar ' + state;
statusMsg.textContent = msg;
}
/** Update step counter. */
function setStep(n) {
stepCountEl.textContent = (n === 0 || n == null) ? '—' : n;
}
/** Apply / remove state class on a box wrapper. */
function setState(index, state) {
const el = document.getElementById(`box-${index}`);
if (!el) return;
el.classList.remove('state-swap','state-sorted','state-left','state-right',
'state-mid','state-elim','state-found');
if (state) el.classList.add(`state-${state}`);
}
/** Update the visible value inside a box (used during swap animation). */
function setBoxValue(index, val) {
const el = document.getElementById(`cell-${index}`);
if (el) el.textContent = val;
}
/** Show L / M / R pointer tags beneath boxes. */
function updatePointers(left, mid, right) {
document.querySelectorAll('.pointer-tag').forEach(el => {
el.className = 'pointer-tag'; el.textContent = '';
});
const tag = (i, label, cls) => {
const el = document.getElementById(`ptag-${i}`);
if (!el) return;
el.classList.add('show', cls);
el.textContent = el.textContent ? el.textContent + '/' + label : label;
};
if (left >= 0) tag(left, 'L', 'tag-left');
if (right >= 0) tag(right, 'R', 'tag-right');
if (mid >= 0) tag(mid, 'M', 'tag-mid');
}
/** Hide all pointer tags. */
function clearPointers() {
document.querySelectorAll('.pointer-tag').forEach(el => {
el.className = 'pointer-tag'; el.textContent = '';
});
}
/** Clear all visual states from every box. */
function clearAllStates() {
for (let i = 0; i < array.length; i++) setState(i, '');
}
// ── Render ───────────────────────────────────────────────────
/**
* Build DOM boxes from the current `array`.
* Also creates an invisible pointer-tag below each box.
*/
function renderArray() {
arrayContainer.innerHTML = '';
pointerRow.innerHTML = '';
emptyState.style.display = array.length ? 'none' : 'flex';
array.forEach((val, i) => {
// Box wrapper
const wrap = document.createElement('div');
wrap.className = 'array-box';
wrap.id = `box-${i}`;
const idx = document.createElement('span');
idx.className = 'box-index';
idx.textContent = i;
const cell = document.createElement('div');
cell.className = 'box-value';
cell.id = `cell-${i}`;
cell.textContent = val;
wrap.append(idx, cell);
arrayContainer.appendChild(wrap);
// Pointer tag
const ptag = document.createElement('div');
ptag.className = 'pointer-tag';
ptag.id = `ptag-${i}`;
pointerRow.appendChild(ptag);
});
}
/**
* Render the clickable chips for every value in the sorted array.
* Clicking a chip sets that value as the target and starts the search.
*/
function renderChips() {
chipsRow.innerHTML = '';
array.forEach(val => {
const chip = document.createElement('button');
chip.className = 'chip';
chip.textContent = val;
chip.addEventListener('click', () => {
if (isRunning) return;
// Highlight the clicked chip
document.querySelectorAll('.chip').forEach(c => c.classList.remove('chip-active'));
chip.classList.add('chip-active');
// Set target input and fire search
targetInput.value = val;
startSearch(val);
});
chipsRow.appendChild(chip);
});
chipsSection.style.display = 'block';
}
// ── Parse Input ──────────────────────────────────────────────
/**
* Parse the array input field.
* Returns { ok: true, values: [...] } or { ok: false, error: '...' }.
*/
function parseArrayInput(raw) {
const parts = raw.trim().split(/[\s,]+/).filter(Boolean);
if (parts.length < 2) return { ok: false, error: 'Enter at least 2 numbers.' };
const nums = [];
for (const p of parts) {
const n = Number(p);
if (!Number.isInteger(n) || n < 1 || n > 999) {
return { ok: false, error: `"${p}" is invalid — use whole numbers between 1 and 999.` };
}
nums.push(n);
}
if (nums.length > 20) return { ok: false, error: 'Maximum 20 numbers allowed.' };
// Remove duplicates, keep insertion order before sort
const unique = [...new Set(nums)];
return { ok: true, values: unique };
}
// ── Animated Bubble Sort ─────────────────────────────────────
/**
* Sorts `array` in-place using Bubble Sort, animating each swap.
* After completion, marks all boxes as 'sorted' (green tint) briefly.
*/
async function animatedBubbleSort() {
const ms = speedMap[parseInt(speedSlider.value, 10)];
const n = array.length;
setStatus('sorting', 'Sorting your array with Bubble Sort…');
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (stopFlag) return;
// Highlight comparing pair
setState(j, 'swap');
setState(j+1, 'swap');
setStatus('sorting', `Comparing index ${j} (${array[j]}) and ${j+1} (${array[j+1]})`);
await delay(ms);
if (stopFlag) return;
if (array[j] > array[j + 1]) {
// Swap values in array and DOM
[array[j], array[j+1]] = [array[j+1], array[j]];
setBoxValue(j, array[j]);
setBoxValue(j+1, array[j+1]);
swapped = true;
}
setState(j, '');
setState(j+1, '');
}
// Mark the last sorted position
setState(n - 1 - i, 'sorted');
if (!swapped) break; // early exit if already sorted
}
// Mark remaining as sorted
for (let i = 0; i < n; i++) setState(i, 'sorted');
setStatus('idle', `✓ Array sorted! Now choose a value to search.`);
await delay(600);
if (stopFlag) return;
// Clear sorted highlights
for (let i = 0; i < n; i++) setState(i, '');
}
// ── Animated Binary Search ───────────────────────────────────
/**
* Performs an animated Binary Search for `target` in `array`.
*/
async function animatedBinarySearch(target) {
const ms = speedMap[parseInt(speedSlider.value, 10)];
let left = 0;
let right = array.length - 1;
let step = 0;
setStatus('searching', `Searching for ${target}…`);
clearAllStates();
clearPointers();
setStep(0);
try {
while (left <= right) {
if (stopFlag) return;
const mid = Math.floor((left + right) / 2);
step++;
setStep(step);
// Highlight active window + mid
for (let i = left; i <= right; i++) setState(i, '');
setState(mid, 'mid');
updatePointers(left, mid, right);
setStatus('searching', `Step ${step}: mid = index ${mid} → value ${array[mid]}`);
await delay(ms);
if (stopFlag) return;
if (array[mid] === target) {
setState(mid, 'found');
clearPointers();
setStatus('found', `✓ Found ${target} at index ${mid} in ${step} step${step > 1 ? 's' : ''}!`);
return;
}
if (array[mid] < target) {
setStatus('searching', `${array[mid]} < ${target} → eliminate left half, move right`);
for (let i = left; i <= mid; i++) setState(i, 'elim');
left = mid + 1;
} else {
setStatus('searching', `${array[mid]} > ${target} → eliminate right half, move left`);
for (let i = mid; i <= right; i++) setState(i, 'elim');
right = mid - 1;
}
await delay(ms * 0.5);
if (stopFlag) return;
}
// Not found
clearPointers();
setStatus('not-found', `✗ ${target} is not in the array. Search ended after ${step} step${step !== 1 ? 's' : ''}.`);
} catch (e) {
if (e !== 'stopped') console.error(e);
}
}
// ── Button Handlers ──────────────────────────────────────────
/** Parse input, animate sort, then unlock search controls. */
async function handleBuild() {
if (isRunning) return;
const { ok, values, error } = parseArrayInput(arrayInput.value);
if (!ok) {
arrayHint.textContent = error;
arrayHint.classList.add('error');
arrayInput.classList.add('error');
return;
}
// Clear any previous error style
arrayHint.classList.remove('error');
arrayInput.classList.remove('error');
arrayHint.textContent = 'Sorting…';
// Lock controls
isRunning = true; stopFlag = false;
buildBtn.disabled = true; randomBtn.disabled = true;
searchBtn.disabled = true; resetBtn.disabled = false;
targetInput.disabled = true;
chipsSection.style.display = 'none';
// Copy into working array and render unsorted first
array = [...values];
renderArray();
setStep(0);
clearPointers();
// Animate the sort
await animatedBubbleSort();
// Done — unlock search
isRunning = false;
buildBtn.disabled = false;
randomBtn.disabled = false;
searchBtn.disabled = false;
targetInput.disabled = false;
arrayHint.textContent = `Array of ${array.length} numbers sorted ✓ — now search a value below.`;
renderChips();
}
/** Fill input with a random set and trigger build. */
function handleRandom() {
if (isRunning) return;
const size = Math.floor(Math.random() * 7) + 8; // 8–14 numbers
const set = new Set();
while (set.size < size) set.add(Math.floor(Math.random() * 150) + 1);
arrayInput.value = Array.from(set).join(', ');
arrayHint.classList.remove('error');
arrayInput.classList.remove('error');
handleBuild();
}
/** Start a binary search for the given target value. */
async function startSearch(target) {
if (isRunning || array.length === 0) return;
if (isNaN(target) || target == null) {
setStatus('not-found', '⚠ Please enter a valid number to search.');
return;
}
isRunning = true; stopFlag = false;
searchBtn.disabled = true;
buildBtn.disabled = true;
randomBtn.disabled = true;
resetBtn.disabled = false;
await animatedBinarySearch(Number(target));
isRunning = false;
searchBtn.disabled = false;
buildBtn.disabled = false;
randomBtn.disabled = false;
}
/** Triggered by "Start Search" button or Enter key. */
function handleSearch() {
const val = targetInput.value.trim();
if (val === '' || isNaN(val)) {
setStatus('not-found', '⚠ Please enter a number to search.');
return;
}
// Clear chip highlight
document.querySelectorAll('.chip').forEach(c => c.classList.remove('chip-active'));
startSearch(parseInt(val, 10));
}
/** Stop everything and restore initial state. */
function handleReset() {
stopFlag = true;
isRunning = false;
clearTimeout(window._animId);
clearAllStates();
clearPointers();
setStep(0);
setStatus('idle', 'Reset. You can search again or build a new array.');
searchBtn.disabled = false;
buildBtn.disabled = false;
randomBtn.disabled = false;
resetBtn.disabled = false;
targetInput.disabled = false;
document.querySelectorAll('.chip').forEach(c => c.classList.remove('chip-active'));
}
// ── Event Listeners ──────────────────────────────────────────
buildBtn.addEventListener('click', handleBuild);
randomBtn.addEventListener('click', handleRandom);
searchBtn.addEventListener('click', handleSearch);
resetBtn.addEventListener('click', handleReset);
targetInput.addEventListener('keydown', e => { if (e.key === 'Enter') handleSearch(); });
arrayInput.addEventListener('keydown', e => { if (e.key === 'Enter') handleBuild(); });
// Clear error styles as user types
arrayInput.addEventListener('input', () => {
arrayInput.classList.remove('error');
arrayHint.classList.remove('error');
arrayHint.textContent = 'Enter at least 2 numbers. Duplicates are removed automatically.';
});