forked from MrTimcakes/Algorithm-Visualiser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlgorithm-Visualiser.js
More file actions
357 lines (315 loc) · 13.5 KB
/
Algorithm-Visualiser.js
File metadata and controls
357 lines (315 loc) · 13.5 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
class algorithmVisualiser{
configVariables(){ // Bodge for ES6 not supporting Public Field Declarations
self.dataSet = {
data: [],
compIndicator: [],
compCount: 0,
swapIndicator: [],
swapCount: 0,
iterationCount: 0,
iteration: () => { self.dataSet.iterationCount++; self.dataSet.swapIndicator = []; self.dataSet.compIndicator = []; },
swap: (x,y) => {
[ self.dataSet.data[x], self.dataSet.data[y] ] = [ self.dataSet.data[y], self.dataSet.data[x] ];
self.dataSet.swapIndicator = [x, y];
self.dataSet.swapCount++;
self.audio.swap();
},
lessthan: (x,y) => { self.audio.comp(); self.dataSet.compIndicator = [x, y]; self.dataSet.compCount++; return self.dataSet.data[x] < self.dataSet.data[y]},
greaterthan: (x,y) => { self.audio.comp(); self.dataSet.compIndicator = [x, y]; self.dataSet.compCount++; return self.dataSet.data[x] > self.dataSet.data[y]},
};
self.options = {
size: 128,
delay: 16,
structure: "Random",
algorithm: "Bubble Sort",
gui: false,
fps: false,
lineColor: "#0000FF",
compColor: "#FF0000",
swapColor: "#00FF00",
lineWidth: 2.5,
fontSize: 15,
displayValues: false,
};
self.audio = {
enabled: true,
volume: 100,
//swapTone: "C4",
swapTone: 350,
compTone: 200,
synth: new Tone.Synth().toMaster(),
swap: () =>{self.audio.synth.triggerAttackRelease(self.audio.swapTone, '1n')},
comp: () =>{self.audio.synth.triggerAttackRelease(self.audio.compTone, '1n')},
};
self.paused = true;
self.ran = false;
}
constructor(canvas, opts = {}) {
self = this;
self.configVariables();
self.configDynamicFunctions();
self.options = {...self.options, ...opts}; // Apply construction options
self.ctx = canvas.getContext('2d');
if(self.options.gui){
var gui = new dat.GUI();
gui.add(self.options, 'algorithm', self.algorithms.map(x => x.name)).name("Algorithm").onFinishChange(self.reset);
gui.add(self.options, 'structure', self.structures.map(x => x.name)).name("Structure").onFinishChange(self.reset);
gui.add(self.options, 'size', 64, 1024, 64).name("Size").onChange(self.reset);
gui.add(self.options, 'delay', 0, 64).name("Delay (ms)");
gui.add(self, 'reset').name("Reset");
gui.add(self, 'startStop').name("Start / Stop");
let advFolder = gui.addFolder("Advanced");
let audioFolder = advFolder.addFolder("Audio");
audioFolder.add(self.audio, 'enabled').name("Enable");
audioFolder.add(self.audio, 'volume').name("Volume").onChange(()=>{Tone.Master.volume = self.audio.volume});
audioFolder.add(self.audio, 'swapTone', 20, 1024).name("Swap Tone");
audioFolder.add(self.audio, 'compTone', 20, 1024).name("Comp Tone");
advFolder.addColor(self.options, 'lineColor');
advFolder.addColor(self.options, 'compColor');
advFolder.addColor(self.options, 'swapColor');
advFolder.add(self.options, 'lineWidth', 0, 15);
advFolder.add(self.options, 'fontSize', 0, 72);
advFolder.add(self.options, 'displayValues');
if(self.options.fps != false && self.options.gui){
self.options.fps = new Stats();
self.options.fps.domElement.height = '48px';
[].forEach.call(self.options.fps.domElement.children, (child) => (child.style.display = ''));
var perfFolder = gui.addFolder("Performance");
var perfLi = document.createElement("li");
self.options.fps.domElement.style.position = "static";
perfLi.appendChild(self.options.fps.domElement);
perfLi.classList.add("gui-stats");
perfFolder.__ul.appendChild(perfLi);
}
}
if(self.options.fps != false && !(self.options.gui)){
self.options.fps = new Stats();
self.options.fps.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
self.options.fps.domElement.style = "position:fixed;top:0;left:0;";
document.body.appendChild( self.options.fps.domElement );
}
self.reset();
self.draw();
}
startStop(){
if(self.paused)
{
self.paused = false;
if (!self.ran)
{
self.algorithms.find(x => x.name === self.options.algorithm).algorithm();
self.ran = true;
}
}
else
self.paused = true;
}
reset(){
self.structures.find(x => x.name === self.options.structure).func();
self.dataSet.iterationCount = 0;
self.dataSet.swapIndicator = [];
self.dataSet.compIndicator = [];
self.dataSet.swapCount = 0;
self.dataSet.compCount = 0;
}
draw(){
if(self.options.fps != false){self.options.fps.begin();}
var ctx = self.ctx;
var width = ctx.canvas.width = ctx.canvas.clientWidth;
var height = ctx.canvas.height = ctx.canvas.clientHeight;
var scaleY = (height / Math.max(...self.dataSet.data));
var lineWidth = self.options.lineWidth || (width/self.dataSet.data.length)+0.5;
for(let i=0;i<self.dataSet.data.length;i++){ // For every element in the dataset, draw its line
ctx.strokeStyle = self.options.lineColor;
ctx.lineWidth = lineWidth;
ctx.beginPath();
let xPos = i*(width/self.dataSet.data.length);
let yPos = height - (self.dataSet.data[i] * scaleY);
if(self.dataSet.compIndicator.includes(i)){ // If the line is currently in a comparison, draw it in that colour
ctx.lineWidth = lineWidth*3;
ctx.strokeStyle = self.options.compColor;
}
if(self.dataSet.swapIndicator.includes(i)){ // If the line is currently in a swap, draw it in that colour
ctx.lineWidth = lineWidth*3;
ctx.strokeStyle = self.options.swapColor;
}
ctx.moveTo(xPos, height);
ctx.lineTo(xPos, yPos);
ctx.stroke();
// Text Above bars
if(self.options.displayValues){
ctx.font = self.options.fontSize + 'px Arial';
var textStr = `${self.dataSet.data[i]}`;
ctx.fillText(textStr, xPos - (ctx.measureText(textStr).width / 2), yPos - 5);
}
}
ctx.font = self.options.fontSize + 'px Arial';
var textStr = `${self.options.algorithm} Iteration: ${self.dataSet.iterationCount} Comparisons: ${self.dataSet.compCount} Swaps: ${self.dataSet.swapCount}`;
ctx.fillText(textStr, 10, self.options.fontSize + 10);
if(self.options.fps != false){self.options.fps.end();}
window.requestAnimationFrame( () => self.draw() );
//window.requestAnimationFrame( this.draw.bind(this) ); // Fix "this" binding
}
async wait(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
configDynamicFunctions(){ // Bodge for ES6 not supporting Public Field Declarations
self.structures = [
{name:"Random", func: ()=>{
self.dataSet.data = Array.from({length: self.options.size}, () => Math.floor(Math.random() * self.options.size));
}},
{name:"Random Unique", func: ()=>{
self.dataSet.data = Array.from(new Array(self.options.size),(v,i)=>i);
for (let i = self.dataSet.data.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[self.dataSet.data[i], self.dataSet.data[j]] = [self.dataSet.data[j], self.dataSet.data[i]];
}
}},
{name:"Reverse Order", func: ()=>{
self.dataSet.data = Array.from(new Array(self.options.size),(v,i)=>self.options.size-i);
}},
{name:"Nearly Sorted", func: ()=>{
// TODO: Make Nearly Sorted Arr
}},
{name:"Few Unique", func: ()=>{
// TODO: Make Arr with a few unique values
}}
]
self.algorithms = [
{name:"Bubble Sort",algorithm: async ()=>{
for (var i = ( self.dataSet.data.length - 1); i >= 0; i--){
for (var j = ( self.dataSet.data.length - i); j > 0; j--){
self.dataSet.iteration(); // Iterate counter etc...
if (self.dataSet.lessthan(j, j-1)){
self.dataSet.swap(j, j-1);
}
while(self.paused)
await self.wait(50);
await self.wait(self.options.delay); // Delay before next iteration
}
}
self.dataSet.swapIndicator = []; // Finished Empty active data
self.dataSet.swapIndicator =[]; // Finished Empty active data
}},
{name:"Quick Sort",algorithm: async ()=>{
var low = 0;
var high = self.dataSet.data.length - 1;
// Create an auxiliary stack and push inital values
//int stack[high - low + 1];
var stack = [];
var top = -1;
stack[++top] = low;
stack[++top] = high;
// Keep popping from stack while is not empty
while (top >= 0) {
// Pop high and low
high = stack[top--];
low = stack[top--];
// Inline Partion Calculation
var partitionIndex = (low - 1);
for (var j = low; j <= high - 1; j++) {
if (self.dataSet.lessthan(j, high)) { // Should be <=
//if (self.dataSet.data[j] <= pivotValue) {
partitionIndex++;
self.dataSet.swap(partitionIndex, j);
await self.wait(self.options.delay); // Delay before next iteration
}
}
self.dataSet.swap(partitionIndex + 1, high);
await self.wait(self.options.delay); // Delay before next iteration
while(self.paused)
await self.wait(50);
partitionIndex++;
// End of Partition
// If there are elements on left side of pivot,
// then push left side to stack
if (partitionIndex - 1 > low) {
stack[++top] = low;
stack[++top] = partitionIndex - 1;
}
// If there are elements on right side of pivot,
// then push right side to stack
if (partitionIndex + 1 < high) {
stack[++top] = partitionIndex + 1;
stack[++top] = high;
}
}
}},
{name:"Selection Sort",algorithm: async ()=>{
for(var i = 0; i < self.dataSet.data.length-1 ; i++) {
var minIdx = i ;
for(var j = i+1; j < self.dataSet.data.length ; j++ ) {
if(self.dataSet.lessthan(j, minIdx)) { //finds the minIdx element
minIdx = j ;
}
await self.wait(self.options.delay); // Delay before next iteration
while(self.paused)
await self.wait(50);
}
self.dataSet.swap(minIdx, i);
}
}},
{
name: "Insertion Sort", algorithm: async () => {
for(let i = 1; i < self.dataSet.data.length; i++){
let value = self.dataSet.data[i];
let j = i - 1;
self.dataSet.compIndicator = [j, i]; self.dataSet.compCount++;
while(j >= 0 && self.dataSet.data[j] > value){
self.dataSet.data[j + 1] = self.dataSet.data[j];
self.dataSet.swapIndicator = [j, j+1]; self.dataSet.swapCount++;
j = j - 1;
await self.wait(self.options.delay);
while(self.paused)
await self.wait(50);
}
self.dataSet.data[j + 1] = value;
await self.wait(self.options.delay);
}
self.dataSet.swapIndicator = []; // Finished Empty active data
self.dataSet.compIndicator = []; // Finished Empty active data
}
},
{
name: "Shell Sort", algorithm: async () => {
// Define a gap distance.
let gap = Math.floor(self.dataSet.data.length / 2);
// Until gap is bigger then zero do elements comparisons and swaps.
while (gap > 0) {
// Go and compare all distant element pairs.
for (let i = 0; i < (self.dataSet.data.length - gap); i += 1) {
let currentIndex = i;
let gapShiftedIndex = i + gap;
while (currentIndex >= 0) {
self.dataSet.iteration(); // Iterate counter
// Compare and swap array elements if needed.
if (self.dataSet.lessthan(gapShiftedIndex, currentIndex)) {
self.dataSet.swap(currentIndex, gapShiftedIndex);
}
await self.wait(self.options.delay); self
gapShiftedIndex = currentIndex;
currentIndex -= gap;
while(self.paused)
await self.wait(50);
}
}
// Shrink the gap.
gap = Math.floor(gap / 2);
}
self.dataSet.swapIndicator = []; // Finished Empty active data
self.dataSet.compIndicator = []; // Finished Empty active data
}
},
];
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* End Class */
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var AV;
window.onload = () => {
let AVCanvas = document.getElementById("algorithm-visualiser");
AV = new algorithmVisualiser(AVCanvas, {gui: true, fps: true});
};