Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created March 9, 2023 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/5d6f5e4a04fd8300ea7b611bdd5be5bb to your computer and use it in GitHub Desktop.
Save sebinsua/5d6f5e4a04fd8300ea7b611bdd5be5bb to your computer and use it in GitHub Desktop.
function layer(N) {
return Math.ceil(Math.sqrt(N));
}
function layerRange(L) {
const start = Math.pow(L - 1, 2) + 1;
const end = Math.pow(L, 2);
return [start, end];
}
function direction(L, axis) {
switch (axis) {
case "y": {
return L % 2 === 0 ? 1 : -1;
}
case "x": {
return L % 2 === 0 ? -1 : 1;
}
default: {
throw new Error(`Invalid axis argument supplied: ${axis}`);
}
}
}
function coord(N, axis) {
const L = layer(N);
const [start, end] = layerRange(L);
const sequenceIndex = N - start;
const midIndex = (end - start) / 2;
const D = direction(L, axis);
switch (D) {
case 1: {
if (sequenceIndex <= midIndex) {
return sequenceIndex + 1;
}
return L;
}
case -1: {
if (sequenceIndex > midIndex) {
return L + D * (sequenceIndex - midIndex);
}
return L;
}
default: {
throw new Error(`Invalid direction generated: ${direction}`);
}
}
}
function y(N) {
return coord(N, "y");
}
function x(N) {
return coord(N, "x");
}
function f(N) {
return [y(N), x(N)];
}
// --------------------
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
function printGrid(grid) {
console.table(grid);
}
// --------------------
console.log("==================");
const grid = [];
for (let N of range(1, 25)) {
console.debug(`${N} = ${f(N)}`);
const [y, x] = f(N);
if (!grid[y - 1]) {
grid[y - 1] = [];
}
grid[y - 1][x - 1] = N;
}
printGrid(grid);
@sebinsua
Copy link
Author

sebinsua commented Mar 9, 2023

@sebinsua
Copy link
Author

sebinsua commented Mar 10, 2023

This is actually a solution to a different problem than the one posed. In the problem posed on cses.fi you are passed (y, x) and must produce n -- while above we've passed n to work out (y, x).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment