Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2019
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function node (coords) {
  2.     this.x = coords.x;
  3.     this.y = coords.y;
  4.     this.red = 0;
  5.     this.blue = 0;
  6.     this.visit = (color, distance) => {
  7.         this[color] = distance;
  8.     };
  9.     return this;
  10. }
  11.  
  12. const MOVE = {
  13.     R: (coords) => {return {x: coords.x+1, y: coords.y+0} },
  14.     L: (coords) => {return {x: coords.x-1, y: coords.y+0} },
  15.     U: (coords) => {return {x: coords.x+0, y: coords.y+1} },
  16.     D: (coords) => {return {x: coords.x+0, y: coords.y-1} },
  17. }
  18.  
  19. const on = (a, b) => a.x === b.x && a.y === b.y
  20.  
  21. const getClosest = (board) => board.filter((node) => node.red && node.blue)
  22.                                    .map(node => Math.abs(node.x) + Math.abs(node.y))
  23.                                    .sort((a, b) => a.distance-b.distance)[0];
  24.  
  25. const getClosestBySignal = (board) => board.filter((node) => node.red && node.blue)
  26.                                            .map(node => node.red+node.blue)
  27.                                            .sort((a, b) => a-b)[0];
  28.  
  29. let board = [];
  30.  
  31. const traverse = (path, color) => {
  32.     path = path.map(move => { return { direction: move.slice(0, 1),
  33.                                        length: move.slice(1) }});
  34.     let coords = {x: 0, y: 0};
  35.     let index = 0;
  36.     let moves = 0;
  37.     path.forEach(move => {
  38.         for(let i = move.length; i > 0; --i) {
  39.             coords = MOVE[move.direction](coords);
  40.             ++moves;
  41.             let currentNode = board.find(node => on(coords, node));
  42.             if(!currentNode) {
  43.                 currentNode = new node(coords);
  44.                 board.push(currentNode);
  45.             }
  46.             currentNode.visit(color, moves);
  47.         }
  48.         console.log(`Move ${++index} of ${path.length} completed for ${color}`);
  49.     });
  50. }
  51.  
  52. traverse(red, "red");
  53. traverse(blue, "blue");
  54. console.log(getClosestBySignal(board));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement