-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChainedHashTable.html
More file actions
582 lines (546 loc) · 20.4 KB
/
ChainedHashTable.html
File metadata and controls
582 lines (546 loc) · 20.4 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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hash Table Visualizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;700&display=swap');
body {
font-family: 'Inter', sans-serif;
}
.mono {
font-family: 'JetBrains Mono', monospace;
}
.node-update {
animation: pulse-green 0.8s ease-in-out;
}
@keyframes pulse-green {
0% {
ring-width: 0px;
transform: scale(1);
}
50% {
ring-width: 4px;
ring-color: #34d399;
transform: scale(1.1);
border-color: #10b981;
}
100% {
ring-width: 0px;
transform: scale(1);
}
}
.slot-highlight {
background-color: #eef2ff;
border-color: #818cf8;
transform: scale(1.05);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
z-index: 10;
}
/* Custom scrollbar for better density */
::-webkit-scrollbar {
height: 8px;
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f5f9;
}
::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
</style>
</head>
<body class="bg-slate-50 text-slate-900 min-h-screen p-4 md:p-6">
<div class="max-w-6xl mx-auto">
<!-- Header -->
<header
class="mb-6 bg-white p-4 rounded-xl shadow-sm border border-slate-200"
>
<div
class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4"
>
<div class="flex items-center gap-3">
<div
class="p-2 bg-indigo-600 rounded-lg text-white shadow-md shadow-indigo-100"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-5 h-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="7" height="7" x="3" y="3" rx="1" />
<rect width="7" height="7" x="14" y="3" rx="1" />
<rect width="7" height="7" x="14" y="14" rx="1" />
<rect width="7" height="7" x="3" y="14" rx="1" />
</svg>
</div>
<div>
<h1 class="text-xl font-bold text-slate-800 leading-tight">
Hash Table Visualizer
</h1>
<p class="text-xs text-slate-400">Chained Collision Handling</p>
</div>
</div>
<div class="flex flex-wrap gap-3 items-center">
<div class="flex flex-col">
<label class="text-[10px] font-bold text-slate-400 uppercase mb-1"
>Table Size</label
>
<select
id="tableSizeSelect"
class="bg-slate-100 border-none rounded-md px-2 py-1.5 text-sm outline-none focus:ring-2 focus:ring-indigo-400 cursor-pointer"
>
<option value="4">4 Slots</option>
<option value="8">8 Slots</option>
<option value="12" selected>12 Slots</option>
<option value="16">16 Slots</option>
<option value="24">24 Slots</option>
<option value="32">32 Slots</option>
</select>
</div>
<div class="flex flex-col">
<label class="text-[10px] font-bold text-slate-400 uppercase mb-1"
>Find Key</label
>
<div class="relative">
<svg
xmlns="http://www.w3.org/2000/svg"
class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
<input
id="searchInput"
type="text"
placeholder="Search..."
class="bg-slate-100 border-none rounded-md pl-7 pr-2 py-1.5 text-sm outline-none focus:ring-2 focus:ring-indigo-400 w-28"
/>
</div>
</div>
<div class="flex gap-2 self-end">
<button
id="addBtn"
class="bg-indigo-600 hover:bg-indigo-700 text-white px-3 py-1.5 rounded-md text-sm font-medium transition-all flex items-center gap-1.5 shadow-sm active:scale-95"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 12h14" />
<path d="M12 5v14" />
</svg>
Add
</button>
<button
id="addTenBtn"
class="bg-indigo-100 hover:bg-indigo-200 text-indigo-700 px-3 py-1.5 rounded-md text-sm font-medium transition-all flex items-center gap-1.5 active:scale-95"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m13 2-2 10h8l-2 10" />
</svg>
+10
</button>
<button
id="clearBtn"
class="bg-white border border-slate-200 hover:bg-red-50 hover:text-red-600 text-slate-600 px-3 py-1.5 rounded-md text-sm font-medium transition-all active:scale-95"
>
Clear
</button>
</div>
</div>
</div>
<!-- Stats Bar -->
<div
class="mt-4 flex flex-wrap items-center gap-x-6 gap-y-2 border-t border-slate-50 pt-4 text-sm"
>
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-400 uppercase"
>Elements:</span
>
<span id="statCount" class="font-bold">0</span>
</div>
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-400 uppercase"
>Collisions:</span
>
<span id="statCollisions" class="font-bold text-amber-600">0</span>
</div>
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-400 uppercase"
>Load:</span
>
<span id="statLoad" class="font-bold text-indigo-600">0.00</span>
</div>
<div class="flex-grow"></div>
<div
id="activityLog"
class="flex items-center gap-2 px-3 py-1 rounded-full bg-slate-50 text-[10px] font-bold text-slate-500 uppercase border border-slate-100"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-3 h-3 text-indigo-500"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>
Last: Ready
</div>
</div>
</header>
<!-- Visualization Area -->
<div
class="bg-white p-4 rounded-xl shadow-sm border border-slate-200 min-h-[400px] overflow-x-auto"
>
<div id="visualizerGrid" class="flex flex-col gap-3">
<!-- Injected via JavaScript -->
</div>
</div>
<!-- Footer -->
<footer
class="mt-6 bg-slate-100 p-4 rounded-xl text-[11px] text-slate-500 grid md:grid-cols-3 gap-4 border border-slate-200"
>
<div>
<p class="font-bold uppercase text-slate-400 mb-1">HTML/JS Version</p>
<p>
This single-page version maintains a unique key policy. Adding an
existing word increments its value instead of creating a new node.
</p>
</div>
<div>
<p class="font-bold uppercase text-slate-400 mb-1">Complexity</p>
<p>
Lookup is <span class="text-indigo-600 mono">O(1)</span> average.
High load factors increase collision probability, leading to
<span class="text-amber-600 mono">O(n)</span> chains.
</p>
</div>
<div>
<p class="font-bold uppercase text-slate-400 mb-1">
Visualization Info
</p>
<p>
The
<span class="text-emerald-500 font-bold">Green Dot</span> represents
a pointer to another node. The
<span class="text-red-400 font-bold">Red Dot</span> indicates a null
pointer (end of chain).
</p>
</div>
</footer>
</div>
<script>
// Data & State
const WORD_LIST = [
'apple',
'banana',
'cherry',
'date',
'elderberry',
'fig',
'grape',
'honey',
'ice',
'joker',
'kiwi',
'lemon',
'mango',
'nut',
'orange',
'pear',
'quince',
'raspberry',
'strawberry',
'tomato',
'ugli',
'vanilla',
'watermelon',
'xenia',
'yam',
'zest',
'alpha',
'beta',
'gamma',
'delta',
'epsilon',
'zeta',
'eta',
'theta',
'iota',
'kappa',
'lambda',
'mu',
'nu',
'xi',
'omicron',
'pi',
'rho',
'sigma',
'tau',
'upsilon',
'phi',
'chi',
'psi',
'omega',
'ace',
'beam',
'coin',
'door',
'echo',
'fuel',
'glow',
'halo',
'iron',
'jade',
'kite',
'leaf',
'mist',
'neon',
'opal',
'plum',
'quartz',
'ruby',
'star',
'tide',
'unit',
'vent',
'wave',
'yarn',
'zinc',
'bolt',
'clay',
'dusk',
'edge',
'film',
'grid',
'haze',
'ink',
'jazz',
'knob',
'link',
'maze',
'node',
'oath',
'path',
'quiz',
'raft',
'silk',
'trap',
'urge',
'vibe',
'whip',
'yoga',
'zeal',
'apex',
];
let state = {
tableSize: 12,
hashTable: [],
highlightedIndex: null,
searchKey: '',
updatedNodeId: null,
};
// DOM Elements
const grid = document.getElementById('visualizerGrid');
const tableSizeSelect = document.getElementById('tableSizeSelect');
const searchInput = document.getElementById('searchInput');
const addBtn = document.getElementById('addBtn');
const addTenBtn = document.getElementById('addTenBtn');
const clearBtn = document.getElementById('clearBtn');
const statCount = document.getElementById('statCount');
const statCollisions = document.getElementById('statCollisions');
const statLoad = document.getElementById('statLoad');
const activityLog = document.getElementById('activityLog');
// Logic
function calculateHash(key, size) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash << 5) - hash + key.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash) % size;
}
function initTable() {
state.hashTable = Array.from({ length: state.tableSize }, () => []);
state.updatedNodeId = null;
state.highlightedIndex = null;
render();
}
function updateStats() {
let count = 0;
let collisions = 0;
state.hashTable.forEach((chain) => {
count += chain.length;
if (chain.length > 1) collisions += chain.length - 1;
});
statCount.textContent = count;
statCollisions.textContent = collisions;
statLoad.textContent = (count / state.tableSize).toFixed(2);
}
function addEntry(key, silent = false) {
const index = calculateHash(key, state.tableSize);
let actionType = 'insert';
let targetId = null;
const chain = state.hashTable[index];
const existingIdx = chain.findIndex((node) => node.key === key);
if (existingIdx !== -1) {
actionType = 'update';
chain[existingIdx].value += 1;
targetId = chain[existingIdx].id;
} else {
const newId = Math.random().toString(36).substr(2, 9);
targetId = newId;
chain.push({ key, value: 1, id: newId });
}
if (!silent) {
state.highlightedIndex = index;
activityLog.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-indigo-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg> Last: ${actionType} "${key}"`;
if (actionType === 'update') {
state.updatedNodeId = targetId;
setTimeout(() => {
state.updatedNodeId = null;
render();
}, 800);
}
render();
setTimeout(() => {
state.highlightedIndex = null;
render();
}, 1000);
}
}
function render() {
updateStats();
const searchIndex = state.searchKey
? calculateHash(state.searchKey, state.tableSize)
: null;
grid.innerHTML = state.hashTable
.map((chain, index) => {
const isHighlighted = state.highlightedIndex === index;
const isSearchTarget = searchIndex === index;
return `
<div class="flex items-start">
<!-- Slot -->
<div class="flex-shrink-0 w-12 h-12 flex flex-col items-center justify-center rounded-lg border-2 transition-all duration-300 ${isHighlighted ? 'slot-highlight' : 'bg-slate-50 border-slate-200'} ${isSearchTarget ? 'ring-2 ring-indigo-200' : ''}">
<span class="text-[8px] font-bold text-slate-400 uppercase">#${index}</span>
<div class="mt-0.5 w-1.5 h-1.5 rounded-full ${chain.length > 0 ? 'bg-indigo-400' : 'bg-slate-300'}"></div>
</div>
<!-- Arrow -->
<div class="flex-shrink-0 h-12 flex items-center px-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 transition-colors ${chain.length > 0 ? 'text-indigo-300' : 'text-slate-100'}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
</div>
<!-- Chain -->
<div class="flex flex-nowrap items-center gap-0">
${
chain.length === 0
? `<div class="h-12 flex items-center text-slate-200 text-[10px] font-mono italic">null</div>`
: chain
.map((node, nodeIdx) => {
const isFound =
state.searchKey &&
node.key === state.searchKey;
const isUpdated =
state.updatedNodeId === node.id;
return `
<div class="relative flex-shrink-0 w-32 h-12 flex flex-col rounded-lg border transition-all duration-300 ${isFound ? 'border-amber-400 bg-amber-50 scale-105 z-10 shadow-lg' : 'border-slate-200 bg-white shadow-sm'} ${isUpdated ? 'ring-4 ring-emerald-400 ring-opacity-50 scale-110 z-20 border-emerald-400' : ''}">
<div class="px-2 py-0.5 text-[8px] font-bold rounded-t-lg transition-colors ${isUpdated ? 'bg-emerald-100 text-emerald-800' : isFound ? 'bg-amber-100 text-amber-700' : 'bg-slate-50 text-slate-400'}">
${nodeIdx === 0 ? 'Head' : 'Node ' + nodeIdx}
</div>
<div class="px-2 py-1 flex justify-between items-center h-full">
<div class="flex flex-col min-w-0">
<span class="font-bold text-xs text-indigo-700 truncate">${node.key}</span>
</div>
<div class="flex flex-col items-end">
<span class="mono text-[10px] px-1 rounded transition-colors ${isUpdated ? 'bg-emerald-500 text-white font-bold' : 'bg-slate-100 text-slate-600'}">
${node.value}
</span>
</div>
</div>
<div class="absolute bottom-1 right-1">
<div class="w-1.5 h-1.5 rounded-full ${nodeIdx === chain.length - 1 ? 'bg-red-300' : 'bg-emerald-300'}"></div>
</div>
</div>
${
nodeIdx < chain.length - 1
? `<div class="flex-shrink-0 px-1.5 flex items-center">
<div class="w-4 h-px bg-slate-200 relative">
<div class="absolute right-0 top-1/2 -translate-y-1/2 border-y-[3px] border-y-transparent border-l-[4px] border-l-slate-200"></div>
</div>
</div>`
: `<div class="flex-shrink-0 px-3 flex items-center text-slate-200 text-[9px] font-mono">/ 0</div>`
}
`;
})
.join('')
}
</div>
</div>
`;
})
.join('');
}
// Event Listeners
tableSizeSelect.addEventListener('change', (e) => {
state.tableSize = parseInt(e.target.value);
initTable();
});
searchInput.addEventListener('input', (e) => {
state.searchKey = e.target.value.toLowerCase();
render();
});
addBtn.addEventListener('click', () => {
const word = WORD_LIST[Math.floor(Math.random() * WORD_LIST.length)];
addEntry(word);
});
addTenBtn.addEventListener('click', () => {
for (let i = 0; i < 10; i++) {
const word = WORD_LIST[Math.floor(Math.random() * WORD_LIST.length)];
addEntry(word, i < 9);
}
});
clearBtn.addEventListener('click', () => {
initTable();
activityLog.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-indigo-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg> Last: Clear`;
});
// Start
initTable();
</script>
</body>
</html>