Created
March 9, 2023 11:29
-
-
Save sebinsua/5d6f5e4a04fd8300ea7b611bdd5be5bb to your computer and use it in GitHub Desktop.
This file contains 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
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); |
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
See: https://codesandbox.io/s/focused-wu-du9nol?file=/src/index.js