xxxxxxxxxx
90
let track = [];
let step;
let ready;
let delimiter = ' ';
this.focus();
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(80);
fill('white');
noStroke();
initData();
}
function initData() {
// track = ['A', 'B', 'C', 'D', 'E', 'F'];
track = [1, 2, 3, 4, 5, 6];
// track = [0, 0, 1, 2, 2, 2, 5, 5]; // Kömal_2025-01_841
textAlign(CENTER, TOP);
step = 1;
ready = false;
noLoop();
}
function displayData() {
background('black');
let s = '';
for (let i = 0; i < track.length - 1; i++) {
s = s + track[i] + delimiter;
}
s = s + track[track.length - 1];
text('# ' + step, width / 2, 0);
text(s, width / 2, height / 2);
}
function nextPermutation(left = 0, right = 0) {
// left = Number of DO-NOT-TOUCH element(s) from left
// right = Number of DO-NOT-TOUCH element(s) from right
let startPos = track.length - 1 - right;
// STEP1: Find the Pivot
let i = startPos;
while (i > 0 && track[i - 1] >= track[i]) { i-- }
if (i <= left) { return false }
// STEP2: Find rightmost element (RME) greater than the Pivot
let j = startPos;
while (track[j] <= track[i - 1]) { j-- }
// STEP3: Swap the Pivot and RME
let temp = track[i - 1];
track[i - 1] = track[j];
track[j] = temp;
// STEP4: Reverse suffix
j = startPos;
while (i < j) {
temp = track[i];
track[i] = track[j];
track[j] = temp;
i++;
j--;
}
return true;
}
function keyPressed() {
if(keyCode === ENTER) {
if (isLooping()) { noLoop(); return; }
if (ready) {
initData();
displayData();
} else { loop() }
}
if(keyCode === ESCAPE & !isLooping() & !ready) {
oneStep();
}
}
function oneStep() {
displayData();
if (nextPermutation() == false) {
ready = true;
noLoop();
textAlign(CENTER, BOTTOM);
text('READY', width / 2, height);
}
step++;
}
function draw() {
oneStep();
}