Help me with a Javascript programming task. I have a GeoJSON with several lines in a…
- User
Help me with a Javascript programming task. I have a GeoJSON with several lines in a row. Also, these lines represent a grid of streets in a real map. Create a recursive function to find a route between two points in that grid.
- Assistant
To accomplish this task, you can use a depth-first search (DFS) algorithm that will explore the grid and find a path between the starting and ending points. Here's a possible implementation in JavaScript using a recursive DFS function:
const geojson = { type: "FeatureCollection", features: [ // Your GeoJSON LineString features here ], }; function neighbors(point, lines) { return lines .filter( (line) => (line.coordinates[0][0] === point[0] && line.coordinates[0][1] === point[1]) || (line.coordinates[1][0] === point[0] && line.coordinates[1][1] === point[1]) ) .map((line) => { if (line.coordinates[0][0] === point[0] && line.coordinates[0][1] === point[1]) { return line.coordinates[1]; } return line.coordinates[0]; }); } function dfs(path, target, lines) { let current = path[path.length - 1]; if (current[0] === target[0] && current[1] === target[1]) { return path; } for (let neighbor of neighbors(current, lines)) { if (!path.some((p) => p[0] === neighbor[0] && p[1] === neighbor[1])) { let newPath = dfs([...path, neighbor], target, lines); if (newPath) { return newPath; } } } return null; } function findRoute(geojson, start, end) { const lines = geojson.features.map((feature) => ({ coordinates: feature.geometry.coordinates, })); return dfs([start], end, lines); } // Usage: const start = [1, 1]; const end = [4, 4]; console.log("Route: ", findRoute(geojson, start, end));
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.