Last active
March 5, 2023 10:09
-
-
Save bernhardfritz/86809449c8a2d551c3ac2aeb930589d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import p8g, { | |
| background, | |
| createCanvas, | |
| height, | |
| line, | |
| noSmooth, | |
| random, | |
| } from 'https://unpkg.com/p8g.js'; | |
| const bubbleSort = (a) => { | |
| let n = a.length; | |
| while (n > 1) { | |
| let newn = 0; | |
| for (let i = 1; i <= n - 1; i++) { | |
| if (a[i - 1] > a[i]) { | |
| [a[i - 1], a[i]] = [a[i], a[i - 1]]; | |
| newn = i; | |
| } | |
| } | |
| n = newn; | |
| } | |
| return a; | |
| }; | |
| const fisherYatesShuffle = (a) => { | |
| const n = a.length; | |
| for (let i = 0; i < n - 2; i++) { | |
| const j = Math.floor(random(i, n)); | |
| [a[i], a[j]] = [a[j], a[i]]; | |
| } | |
| return a; | |
| }; | |
| function* makeIterator(fn, a) { | |
| const steps = []; | |
| const handler = { | |
| set(target, p, newValue) { | |
| steps.push([p, newValue]); | |
| target[p] = newValue; | |
| return true; | |
| }, | |
| }; | |
| const proxy = new Proxy([...a], handler); | |
| fn(proxy); | |
| for (const step of steps) { | |
| yield step; | |
| } | |
| } | |
| const n = 100; | |
| const sorted = [...Array(n).keys()]; | |
| let it, a; | |
| const init = () => { | |
| const unsorted = fisherYatesShuffle(sorted); | |
| it = makeIterator(bubbleSort, unsorted); | |
| a = [...unsorted]; | |
| }; | |
| init(); | |
| p8g.draw = () => { | |
| background(255); | |
| noSmooth(); | |
| a.forEach((y, x) => { | |
| line(x, height, x, height - y); | |
| }); | |
| const { value, done } = it.next(); | |
| if (done) { | |
| init(); | |
| } else { | |
| const [x, y] = value; | |
| a[x] = y; | |
| } | |
| }; | |
| createCanvas(n, n); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment