I'm facing an issue with a puzzle called "A child's play" on Codingame. My coding language is typescript!
The task is as follows:
Recently, playful programming has become popular in elementary schools where students use assembly blocks to program small robots. This helps them learn programming at a young age while enhancing their logic and spatial perception.
In this scenario, you are a student in one of these schools. Your teacher has set up a circuit for your robot, specified the number of moves n it can make, and now you must determine the final position of the robot after execution.
To solve this, you need to understand certain principles of robot operation.
– If the robot encounters an obstacle represented by #, it turns right until there are no more obstacles ahead. If it is on an empty area denoted by ., it continues moving straight.
– The robot initially moves upward.
– The robot stops after n moves.
– The top left corner represents the coordinates (0,0).
– The robot's environment is shown below, with O indicating the initial position of the robot:
...#........
...........#
............
............
..#O........
..........#.
I am stuck at test 4 because my solution is not optimized. I receive the following message in the console: The process timed out. This may mean that your solution is not optimized enough to handle some cases.
I have tried changing the loop to a "while" loop and adjusting the "switch" condition to an "if-else" condition. Can someone assist me in finding a better solution or another approach to pass the tests?
var inputs: string[] = readline().split(' ');
const w: number = parseInt(inputs[0]);
const h: number = parseInt(inputs[1]);
const n: number = parseInt(readline());
let zone: string[][] = [];
let robot: robot = { x: 0, y: 0 };
interface robot {
x: number,
y: number
}
for (let i = 0; i < h; i++) {
const line: string = readline();
zone = [...zone, line.split('')]
}
zone.forEach((line, y) => {
line.forEach((place, x) => {
if (place === "O") {
robot.x = x;
robot.y = y;
}
})
})
function getLoc(robot: robot, zone: string[][], tours: number) {
let direct: string = "T";
var i = 0;
while (i < tours) {
if (direct === "T") {
if (zone[robot.y - 1][robot.x] === '#') {
robot.x++;
direct = "R";
} else {
robot.y--;
}
} else if (direct === "R") {
if (zone[robot.y][robot.x + 1] === '#') {
robot.y++;
direct = "B";
} else {
robot.x++;
}
} else if (direct === "B") {
if (zone[robot.y + 1][robot.x] === '#') {
robot.x--;
direct = "L";
} else {
robot.y++;
}
} else if (direct === "L") {
if (zone[robot.y][robot.x - 1] === '#') {
robot.y--;
direct = "T";
} else {
robot.x--;
}
}
i++;
}
return robot
}
console.time("getLoc")
let res: robot = getLoc(robot, zone, n);
console.timeEnd("getLoc")
console.log(`${res.x} ${res.y}`)