curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645f.md
Given an array of strings representing your trail map, return a string of the moves needed to get to your goal.
The given strings will contain the values:
"C": Your current location"G": Your goal"T": Traversable parts of the trail"-": Untraversable parts of the mapReturn a string with the moves needed to follow the trail from your location to your goal where:
"R" is a move right
"D" is a move down
"L" is a move left
"U" is a move up
There will always be a single continuous trail, without any branching, from your current location to your goal.
Each trail location will have a maximum of two traversable locations touching it.
For example, given:
[
"-CT--",
"--T--",
"--TT-",
"---T-",
"---G-"
]
Return "RDDRDD".
navigateTrail(["-CT--", "--T--", "--TT-", "---T-", "---G-"]) should return "RDDRDD".
assert.equal(navigateTrail(["-CT--", "--T--", "--TT-", "---T-", "---G-"]), "RDDRDD");
navigateTrail(["-----", "--TTG", "--T--", "--T--", "CTT--"]) should return "RRUUURR".
assert.equal(navigateTrail(["-----", "--TTG", "--T--", "--T--", "CTT--"]), "RRUUURR");
navigateTrail(["-C----", "TT----", "T-----", "TTTTT-", "----G-"]) should return "DLDDRRRRD".
assert.equal(navigateTrail(["-C----", "TT----", "T-----", "TTTTT-", "----G-"]), "DLDDRRRRD");
navigateTrail(["--------", "-CTTT---", "----T---", "---GT---", "--------"]) should return "RRRDDL".
assert.equal(navigateTrail(["--------", "-CTTT---", "----T---", "---GT---", "--------"]), "RRRDDL");
navigateTrail(["TTTTTTT-", "T-----T-", "T-----T-", "TTTT--TG", "---C----"]) should return "ULLLUUURRRRRRDDDR".
assert.equal(navigateTrail(["TTTTTTT-", "T-----T-", "T-----T-", "TTTT--TG", "---C----"]), "ULLLUUURRRRRRDDDR");
function navigateTrail(map) {
return map;
}
function navigateTrail(map) {
const rows = map.length;
const cols = map[0].length;
const directions = [
[0, 1, "R"],
[1, 0, "D"],
[0, -1, "L"],
[-1, 0, "U"],
];
let row, col;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (map[r][c] === "C") {
row = r;
col = c;
}
}
}
let result = "";
let prev = null;
while (map[row][col] !== "G") {
for (let [dr, dc, move] of directions) {
const newRow = row + dr;
const newCol = col + dc;
if (
newRow >= 0 &&
newRow < rows &&
newCol >= 0 &&
newCol < cols &&
(map[newRow][newCol] === "T" ||
map[newRow][newCol] === "G") &&
(!prev || newRow !== prev[0] || newCol !== prev[1])
) {
result += move;
prev = [row, col];
row = newRow;
col = newCol;
break;
}
}
}
return result;
}