Created
April 7, 2026 17:08
-
-
Save tatsuyax25/2d688c3ca5bc38a4a21845438d78def8 to your computer and use it in GitHub Desktop.
A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell
This file contains hidden or 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
| /** | |
| * @param {number} width | |
| * @param {number} height | |
| */ | |
| var Robot = function(width, height) { | |
| this.w = width; | |
| this.h = height; | |
| // Perimeter length | |
| this.P = 2 * (width + height) - 4; | |
| // Precompute perimeter path | |
| this.path = []; | |
| // 1. Bottom edge (east) | |
| for (let x = 0; x < width; x++) { | |
| this.path.push([x, 0, "East"]); | |
| } | |
| // 2. Right edge (north) | |
| for (let y = 1; y < height; y++) { | |
| this.path.push([width - 1, y, "North"]); | |
| } | |
| // 3. Top edge (west) | |
| for (let x = width - 2; x >= 0; x--) { | |
| this.path.push([x, height - 1, "West"]); | |
| } | |
| // 4. Left edge (south) | |
| for (let y = height - 2; y >= 1; y--) { | |
| this.path.push([0, y, "South"]); | |
| } | |
| // Current index on perimeter | |
| this.idx = 0; | |
| }; | |
| /** | |
| * @param {number} num | |
| * @return {void} | |
| */ | |
| Robot.prototype.step = function(num) { | |
| if (this.P === 0) return; // degenerate case (not needed per contraints) | |
| const old = this.idx; | |
| this.idx = (this.idx + num) % this.P; | |
| // Correct loop-detection logic | |
| this.justLooped = (this.idx === 0 && num > 0); | |
| }; | |
| /** | |
| * @return {number[]} | |
| */ | |
| Robot.prototype.getPos = function() { | |
| const [x, y] = this.path[this.idx]; | |
| return [x, y]; | |
| }; | |
| /** | |
| * @return {string} | |
| */ | |
| Robot.prototype.getDir = function() { | |
| let dir = this.path[this.idx][2]; | |
| // Apply the corner case override | |
| if (this.idx === 0 && this.justLooped) { | |
| dir = "South"; | |
| } | |
| return dir; | |
| }; | |
| /** | |
| * Your Robot object will be instantiated and called as such: | |
| * var obj = new Robot(width, height) | |
| * obj.step(num) | |
| * var param_2 = obj.getPos() | |
| * var param_3 = obj.getDir() | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment