Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function node (coords) {
- this.x = coords.x;
- this.y = coords.y;
- this.red = 0;
- this.blue = 0;
- this.visit = (color, distance) => {
- this[color] = distance;
- };
- return this;
- }
- const MOVE = {
- R: (coords) => {return {x: coords.x+1, y: coords.y+0} },
- L: (coords) => {return {x: coords.x-1, y: coords.y+0} },
- U: (coords) => {return {x: coords.x+0, y: coords.y+1} },
- D: (coords) => {return {x: coords.x+0, y: coords.y-1} },
- }
- const on = (a, b) => a.x === b.x && a.y === b.y
- const getClosest = (board) => board.filter((node) => node.red && node.blue)
- .map(node => Math.abs(node.x) + Math.abs(node.y))
- .sort((a, b) => a.distance-b.distance)[0];
- const getClosestBySignal = (board) => board.filter((node) => node.red && node.blue)
- .map(node => node.red+node.blue)
- .sort((a, b) => a-b)[0];
- let board = [];
- const traverse = (path, color) => {
- path = path.map(move => { return { direction: move.slice(0, 1),
- length: move.slice(1) }});
- let coords = {x: 0, y: 0};
- let index = 0;
- let moves = 0;
- path.forEach(move => {
- for(let i = move.length; i > 0; --i) {
- coords = MOVE[move.direction](coords);
- ++moves;
- let currentNode = board.find(node => on(coords, node));
- if(!currentNode) {
- currentNode = new node(coords);
- board.push(currentNode);
- }
- currentNode.visit(color, moves);
- }
- console.log(`Move ${++index} of ${path.length} completed for ${color}`);
- });
- }
- traverse(red, "red");
- traverse(blue, "blue");
- console.log(getClosestBySignal(board));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement