-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitches.html
More file actions
543 lines (441 loc) · 15.3 KB
/
switches.html
File metadata and controls
543 lines (441 loc) · 15.3 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
<!DOCTYPE html>
<html>
<!--
Martin Bridge, Apr 2023
Inspired by Ben Sparks' Numberphile video on the switches (aka lockers) problem
https://www.youtube.com/watch?v=-UBDRX6bk-A
26-may-2023 Martin Bridge HTML inputs, play/pause, fit to window
31-may-2023 Martin Bridge Show hot switches, Change delay on plan/pause
31-may-2023 Martin Bridge Minor style changes
31-may-2023 Martin Bridge Removed debug from popup
31-may-2023 Martin Bridge Added gap between switches
01-jun-2023 Martin Bridge Popup info box
18-jun-2023 Martin Bridge Centre the canvas
30-dec-2023 Martin Bridge Move common style to separate files
-->
<head>
<link href="main.css" media="all" rel="stylesheet" type="text/css" />
<link href="buttons.css" media="all" rel="stylesheet" type="text/css" />
<style>
#canvContainer {
width: 100%;
text-align: center;
}
#myCanvas {
display: inline;
}
#actionpanel {
display: grid;
grid-template-columns: 300px 220px 1fr;
column-gap: 10px;
background-color: #333;
padding: 10px;
margin-bottom: 10px;
}
#inputpanel {
display: grid;
grid-template-columns: 3fr 1fr;
column-gap: 10px;
max-width: 270px;
row-gap: 2px;
}
#buttonpanel {
gap: 5px;
display: grid;
grid-template-areas:
'btn1 btn1'
'btn2 btn2'
'a a '
'txt sel'
;
max-width: 300px;
}
#start_btn {
grid-area: btn1;
}
#pause_btn {
grid-area: btn2;
}
#hot_lbl {
grid-area: txt;
display: flex;
/* establish flex container */
flex-direction: column;
/* make main axis vertical */
justify-content: center;
/* center items vertically */
}
#hot_select {
grid-area: sel;
display: flex;
justify-content: right;
}
#textpanel {
display: inline;
margin-left: 30px;
padding: 5px;
background-color: #202020;
}
.popup {
font-size: 10pt;
border-collapse: collapse;
position: absolute;
background: #333333;
visibility: hidden;
pointer-events: none;
min-width: 100px;
padding: 5px;
}
.popup.is-active {
visibility: visible;
pointer-events: auto;
}
#clicktable {
border-collapse: collapse;
}
#clicktable td {
border: 1px solid #aaa;
padding: 0.1em 0.5em 0.1em 0.5em;
}
#clicked, #factors {
max-width: 600px;
line-height: 2em;
overflow-wrap: break-word;
}
sup { vertical-align: top; position: relative; top: -0.5em; }
</style>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-GF0VL3FQMY"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-GF0VL3FQMY');
</script>
<script>
/* TODO
Separately selectable switch size vs auto size (dependent input fields)
Prevent canvas size exceeding maximum dimensions
Add switch numbers when size allows
Put #flips so far back into popup
Problem: If gap * cols is greater than window width, things go wrong!!
*/
var canvas;
var canvasContext;
var elPopup;
var elBody;
var cols;
var rows;
var person;
var nswitches;
var switch_size;
var switch_gap = 1;
var switches;
var flips;
var delay_ms;
var show_activations = false; // Display #activations instead of switch state
var show_info = false; // Show info popup
var timer = 0;
var running = true;
onColor = '#33dd00';
offColor = '#303030';
const el = (sel, par) => (par || document).querySelector(sel);
function init() {
// Note: Maximum canvas dimension 32,767 x 32,767
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas
cols = parseInt(el('#ncols').value);
nswitches = parseInt(el('#nswitches').value);
delay_ms = parseInt(el('#delayms').value);
switch_gap = parseInt(el('#sw_gap').value);
// console.log(`cols = ${cols}`);
// console.log(`nswitches = ${nswitches}`);
// Last row could be incomplete
if (nswitches % cols == 0)
rows = nswitches / cols;
else
rows = Math.floor(nswitches / cols) + 1;
// If supplied as rows & cols
// rows = parseInt(el('#nrows').value);
// nswitches = rows * cols;
(switches = []).length = nswitches + 1;
switches.fill(1); // Faster initialisation of switches array
(flips = []).length = nswitches + 1;
flips.fill(0); // No of times switch is flipped
person = 0;
// In case we have already been running...
if (timer != 0) {
clearInterval(timer);
timer = 0;
}
elBody = el('body');
canvContainer = el('#canvContainer');
canvas = el('#myCanvas');
canvas.width = canvContainer.clientWidth;
switch_size = Math.floor((canvas.width - (cols - 1) * switch_gap) / cols);
canvas.width = cols * (switch_size + switch_gap);
canvas.height = rows * (switch_size + switch_gap);
// console.log(`Sw Size= ${switch_size} canvas (w, h): ${canvas.width}, ${canvas.height}`);
canvas = el('#myCanvas');
}
function play_pause() {
running = !running;
}
function start_animation() {
init();
canvasContext = canvas.getContext('2d');
canvas.addEventListener('click', showData);
elBody.addEventListener('click', showPopup);
running = true;
timer = setInterval(flip_switches, delay_ms);
// A quick way to just show the squares
// squareNumbers(lines=true);
}
function draw_switch(n) {
// Canvas starts at 0,0
// Switches, row & col start at 1
x = (switch_size + switch_gap) * ((n - 1) % cols);
y = (switch_size + switch_gap) * Math.floor((n - 1) / cols);
if (switches[n] == 1)
canvasContext.fillStyle = offColor;
else
canvasContext.fillStyle = onColor;
// Color a Green-Red scale to show how many times switches are flipped
if (show_activations) {
hsl = numberToHsl(flips[n]);
canvasContext.fillStyle = `${hsl}`
}
canvasContext.fillRect(x, y, switch_size, switch_size);
}
function redraw_all() {
// Redraw current state of switches in case display type (state vs activations has changed)
for (s = 1; s <= nswitches; s++)
draw_switch(s);
}
function flip_switches() {
if (running) {
person++;
document.getElementById('personid').innerHTML = person;
// Flip all multiples of current person
for (var switch_num = person; switch_num <= nswitches; switch_num += person) {
// Invert the switch value
switches[switch_num] = 1 - switches[switch_num];
// Increment the number of times the switch is flipped
flips[switch_num]++;
// Redraw the switch
draw_switch(switch_num);
}
}
if (person >= nswitches) {
clearInterval(timer);
running = false;
// cancelAnimationFrame(timer);
}
else {
// Setting a new time/animation frame here seems to cause JS to run
// faster by skipping frames dues to multiple threads (?)
if (delay_ms == 0) {
timer2 = requestAnimationFrame(flip_switches);
}
}
}
/*
* Populate the usually hidden data table when a switch is clicked
*/
function showData(event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
col = Math.floor(x / (switch_size + switch_gap)) + 1;
row = Math.floor(y / (switch_size + switch_gap)) + 1;
let switchn = (row - 1) * cols + col;
let sqrt_s = Math.sqrt(switchn);
if (Math.floor(sqrt_s) == sqrt_s)
sqrt = ` = ${sqrt_s}<sup>2</sup>`;
else
sqrt = '';
let ff = getFactors(switchn);
fstr = `${ff.numFactors}: ${ff.factorList}`;
// Write current selected switch to screen
document.getElementById('clicked').innerHTML = `${switchn} ${sqrt} (r${row}, c${col})`
document.getElementById('factors').innerHTML = `${fstr}`
var pixelData = canvasContext.getImageData(x, y, 1, 1).data;
r = pixelData[0];
g = pixelData[1];
b = pixelData[2];
a = pixelData[3];
}
/*
* A test function to directly plot the square numbers on the grid
*/
function squareNumbers(lines = false) {
let sqrt_n = Math.sqrt(nswitches);
var old_x = 0;
var old_y = 0;
canvasContext.lineWidth = 1;
canvasContext.strokeStyle = '#ddd';
for (var s = 1; s <= sqrt_n; s++) {
s_sqr = s * s;
x = switch_size * ((s_sqr - 1) % cols);
y = switch_size * Math.floor((s_sqr - 1) / cols);
canvasContext.fillStyle = onColor;
canvasContext.fillRect(x, y, switch_size, switch_size);
if (lines) {
canvasContext.beginPath();
canvasContext.moveTo(old_x, old_y);
canvasContext.lineTo(x, y);
canvasContext.stroke();
}
old_x = x;
old_y = y;
}
clearInterval(timer);
}
function getFactors(num) {
let factorList = "";
let numFactors = 0;
let sep = "";
for (let i = 1; i <= num; i++) {
if (num % i == 0) {
factorList += `${sep}${i}`;
sep = ",";
numFactors++;
}
}
return { numFactors, factorList };
}
function numberToHsl(num) {
// Convert range 0 - 50 into Green -> Red (120 to 0 in hue)
let min_input = 0;
let max_input = 40;
let hue0 = 120;
let hue1 = 0;
var hue = hue0 + (hue1 - hue0) * (num - 1) / (max_input - min_input);
if (hue < hue1) hue = 0;
return 'hsl(' + hue + ', 100%, 40%)';
}
/*
* Pop up the data table
*/
const showPopup = (evt) => {
// Get clicked target
const elTarget = evt.target;
// Close currently open popup (if any):
if (elPopup) elPopup.classList.remove("is-active");
// Get initiator button
const elBtn = elTarget.closest("[data-popup]");
// Not a valid button
if (!elBtn) return;
// Get the popup
elPopup = el(elBtn.dataset.popup);
// No matching popup in this page, do nothing
if (!elPopup) return;
// Get its parent (BODY) so that we can calculate the min max available space
const elParent = elPopup.parentElement;
// Position:
const absX = evt.clientX + window.scrollX;
const absY = evt.clientY + window.scrollY;
const bcrParent = elParent.getBoundingClientRect();
const bcrPopup = elPopup.getBoundingClientRect();
const maxX = bcrParent.width - bcrPopup.width;
const maxY = bcrParent.height - bcrPopup.height;
const x = Math.max(0, Math.min(absX, maxX));
const y = Math.max(0, Math.min(absY, maxY));
// Show popup
Object.assign(elPopup.style, {
left: `${x}px`,
top: `${y}px`,
});
elPopup.classList.add("is-active");
};
function toggle_display() {
show_activations = !show_activations;
redraw_all();
}
function set_show(showtype) {
show_activations = (showtype == 'activations');
redraw_all();
}
function toggle_info() {
show_info = !show_info;
q = document.getElementById("info");
let vis = ((show_info) ? "visible" : "hidden");
q.style.visibility = vis;
}
</script>
</head>
<body>
<h3>Switches</h3>
<div id="actionpanel">
<div id="inputpanel">
<!-- <label for="nrows">Rows</label>
<input id="nrows" size="9" value="10" required pattern="[0-9]+">
<label for="ncols">Cols</label>
<input id="ncols" size="9" value="10" required pattern="[0-9]+"> -->
<label for="nswitches">Number of switches</label>
<input id="nswitches" size="9" value="10000" required pattern="[0-9]+">
<label for="ncols">Switches per row</label>
<input id="ncols" size="8" value="100" required pattern="[0-9]+">
<label for="delayms">Animation delay (ms)</label>
<input id="delayms" size="8" value="10" required pattern="[0-9]+">
<label for="sw_gap">Gap (pixels)</label>
<input id="sw_gap" size="8" value="1" required pattern="[0-9]+">
<label id="person_lbl" for="personid">Current Person</label>
<span id="personid">0</span>
</div>
<div id="buttonpanel">
<button id="start_btn" onclick="start_animation()">Go</button>
<button id="pause_btn" onclick="play_pause()">Pause / Continue</button>
<span id="hot_lbl">Show hot switches?</span>
<div id="hot_select">
<label class="switch">
<input type="checkbox" id="hot_select" onclick="toggle_display()">
<span id="hot_slider" class="xslider round"></span>
</label>
</div>
</div>
<div id="textpanel">
Inspired by Ben Sparks' <a href="https://www.youtube.com/watch?v=-UBDRX6bk-A" target="_blank">Numberphile
video</a> on the switches (aka lockers) problem.
<br /><br />
<br />
This is a work-in-progress. Info <a href="#" onclick="toggle_info()">here</a>.
<br /><br />
Martin Bridge, 2023
<div id="info" class="info" onclick="toggle_info()">
The switch display is clickable - it will show the current switch and it's factors.
<p>Quirks:</p>
<ul>
<li>
If the animation doesn't appear, it's likely that the required canvas size
exceeds the maximum canvas size - reduce the number of switches, or increase the switches per
row. (I need to fix this)
<br>
e.g. for 1,000,000 switches, use 1,000 per row
</li>
</ul>
<p>
Feedback welcome: <a href="https://github.com/bridgem/animations" target="_blank">
https://github.com/bridgem/animations</a>
</p>
Click this box to dismiss
</div>
</div>
</div>
<!-- Hidden table to pop up when switch display is clicked -->
<div id="infotable" class="popup">
<table id="clicktable">
<tr>
<td class="field_name">Switch</td>
<td class="data" id="clicked">55</td>
</tr>
<tr>
<td class="field_name">Factors</td>
<td class="data" id="factors">55</td>
</tr>
</table>
</div>
<div id="canvContainer" data-popup="#infotable">
<canvas id="myCanvas" width="1" height="1"></canvas>
</div>
</body>
</html>