Skip to content

Instantly share code, notes, and snippets.

@bernhardfritz
Created March 20, 2023 20:04
Show Gist options
  • Select an option

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

Select an option

Save bernhardfritz/e197e89a91af2582a2af44be9d8bcb00 to your computer and use it in GitHub Desktop.
import p8g, {
background,
createCanvas,
height,
line,
noSmooth,
random,
} from 'https://unpkg.com/p8g.js';
const merge = (left, right) => {
const result = [];
const leftValues = left.values();
const rightValues = right.values();
let leftValue = leftValues.next();
let rightValue = rightValues.next();
while (!leftValue.done && !rightValue.done) {
if (leftValue.value <= rightValue.value) {
result.push(leftValue.value);
leftValue = leftValues.next();
} else {
result.push(rightValue.value);
rightValue = rightValues.next();
}
}
while (!leftValue.done) {
result.push(leftValue.value);
leftValue = leftValues.next();
}
while (!rightValue.done) {
result.push(rightValue.value);
rightValue = rightValues.next();
}
return result;
}
const mergeSort = (a, i = 0, n = a.length) => {
if (n <= 1) {
return a;
}
const h = Math.floor(n / 2);
mergeSort(a, i, h);
mergeSort(a, i + h, n - h);
const merged = merge(a.slice(i, i + h), a.slice(i + h, i + n));
for (let j = i; j < i + n; j++) {
a[j] = merged[j - i];
}
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(mergeSort, 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