Created
January 20, 2022 17:50
-
-
Save silkyfray/18b1ea07ae262003cbb46bf86f942a03 to your computer and use it in GitHub Desktop.
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
// const MAX_GRID_Y = 10; | |
// const MAX_GRID_X = 10; | |
// const START_POS_Y = 0; | |
// const START_GRID_X = 0; | |
interface Coordinate { | |
x: number; | |
y: number; | |
} | |
const MAX_COORD = { | |
x: 9, | |
y: 9 | |
} | |
/** | |
* Asssume 0,0 is the minimum | |
* @param commandsSequence | |
* @param startCoord | |
*/ | |
export const isRobotPositionValid = (commandsSequence: string, startCoord: Coordinate): boolean => { | |
const robotEndPosition = moveRobot(commandsSequence); | |
// check if robots is in the boundary for the box | |
return robotEndPosition.y >= 0 && robotEndPosition.y <= MAX_COORD.y && robotEndPosition.x >= 0 && robotEndPosition.x <= MAX_COORD.x; | |
} | |
export const moveRobot = (commandsSequence: string): Coordinate => { | |
// split commands from string | |
const commands = commandsSequence.split(" "); | |
const currCoord = { x: 0, y: 0 }; | |
// for each command move robot | |
commands.forEach(command => { | |
switch (command) { | |
case 'N': | |
currCoord.y = currCoord.y + 1; | |
break; | |
case 'S': | |
currCoord.y = currCoord.y - 1; | |
break; | |
case 'W': | |
currCoord.x = currCoord.x - 1; | |
break; | |
case 'E': | |
currCoord.x = currCoord.x + 1; | |
break; | |
} | |
}); | |
return currCoord; | |
} | |
// test cases | |
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
import { isRobotPositionValid, moveRobot } from '.' | |
describe("Pairing test", () => { | |
it("expect robot to end at 4,4", () => { | |
const result = moveRobot("N E N E N E N E"); | |
expect(result.x).toBe(4); | |
expect(result.y).toBe(4); | |
}) | |
it("should return true when the robot is outside the grid", () => { | |
const result = isRobotPositionValid("N E N E N E N E", { x: 0, y: 0 }); | |
expect(result).toBe(true); | |
}) | |
it("should return false when the robot is outside the grid", () => { | |
const result = isRobotPositionValid("N W", { x: 0, y: 0 }); | |
expect(result).toBe(false); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment