8_common.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * Parse the input into a string of directions and a list of nodes and their child nodes
  3. *
  4. * @param {string[]} map The array of lines representing the map
  5. * @returns {[string, MapNodeTree]} A string of the directions to take and the node tree for the map
  6. */
  7. export function ParseMap(map: string[]): [string, MapNodeTree] {
  8. const tree: MapNodeTree = {};
  9. const directions = map.shift() || "";
  10. // Discard empty line
  11. map.shift();
  12. let nodeLine:string|undefined = "";
  13. while(nodeLine = map.shift()) {
  14. const [id, leftNode, rightNode] = Array.from(nodeLine.matchAll(/(\w{3})/g), (match) => match[1]);
  15. if (!id || !leftNode || !rightNode) {
  16. throw new Error(`Failed to parse line: ${nodeLine}\n\tid: ${id}\n\tleftNode: ${leftNode}\n\trightNode: ${rightNode}`);
  17. }
  18. tree[id] = {L: leftNode, R: rightNode};
  19. }
  20. return [directions, tree];
  21. }
  22. /**
  23. * Find the ID of the next node to visit
  24. *
  25. * @param {string} directions The entire string of directions
  26. * @param {MapNodeTree} map A list of nodes and their child nodes
  27. * @param {keyof MapNodeTree} currentNode The ID of the node we're current at
  28. * @param {number} stepsTaken The amount of steps already taken in the trek
  29. * @returns {keyof MapNodeTree|undefined} The next node ID, or undefined if none was found
  30. */
  31. export function GetNextNodeInMap(directions: string, map: MapNodeTree, currentNode: keyof MapNodeTree, stepsTaken: number): keyof MapNodeTree|undefined {
  32. let nextNodeID: keyof MapNodeTree|undefined = undefined;
  33. // Ensure the current node exists
  34. if (map[currentNode]) {
  35. // Get the next direction to travel in as a looping index of the directions string
  36. const nextDirection = directions[stepsTaken % directions.length] as "L"|"R";
  37. // Store the next node ID
  38. nextNodeID = map[currentNode][nextDirection];
  39. }
  40. return nextNodeID;
  41. }
  42. /**
  43. * An object representing a tree of nodes
  44. */
  45. export type MapNodeTree = {
  46. /** The ID of the node */
  47. [NodeID: string]: {
  48. /** The ID of the node to the left of this one */
  49. L: string,
  50. /** The ID of the node to the right of this one */
  51. R: string,
  52. },
  53. };