Skip to content

Instantly share code, notes, and snippets.

@bernhardfritz
Last active April 13, 2023 20:53
Show Gist options
  • Select an option

  • Save bernhardfritz/c5b47346de4a5158aff4992b8ee4b008 to your computer and use it in GitHub Desktop.

Select an option

Save bernhardfritz/c5b47346de4a5158aff4992b8ee4b008 to your computer and use it in GitHub Desktop.
import p8g, {
background,
createCanvas,
height,
line,
noSmooth,
random,
} from 'https://unpkg.com/p8g.js';
const insertionSort = (a) => {
const n = a.length;
for (let i = 1; i < n; i++) {
for (let j = i; j > 0 && a[j - 1] > a[j]; j--) {
[a[j], a[j - 1]] = [a[j - 1], a[j]];
}
}
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(insertionSort, 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