Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fsPromises = require('fs').promises;
  2.  
  3. function getLimits(array) {
  4.     let xmax = 0;
  5.     let xmin = 0;
  6.     let ymax = 0;
  7.     let ymin = 0;
  8.  
  9.     let x = 0;
  10.     let y = 0;
  11.  
  12.     array.forEach(elem => {
  13.         let direction = elem[0];
  14.         let distance = parseInt(elem.substr(1), 10);
  15.         let xdifference = 0;
  16.         let ydifference = 0;
  17.         switch(direction) {
  18.             case "R":
  19.                 xdifference += distance;
  20.                 x += xdifference;
  21.                 xmax = Math.max(x, xmax);
  22.                 xdifference += distance;
  23.                 break;
  24.             case "L":
  25.                 xdifference -= distance;
  26.                 x -= xdifference;
  27.                 xmin = Math.min(x, xmin);
  28.                 break;
  29.             case "U":
  30.                 ydifference += distance;
  31.                 y += ydifference;
  32.                 ymax = Math.max(y, ymax);
  33.             case "D":
  34.                 ydifference -= distance;
  35.                 y -= ydifference;
  36.                 ymin = Math.min(y, ymin);
  37.         }
  38.     })
  39.     return {
  40.         xmax, xmin, ymax, ymin
  41.     };
  42. }
  43.  
  44. function combineLimits(limits1, limits2) {
  45.     return {
  46.         xmax: Math.max(limits1.xmax, limits2.xmax),
  47.         xmin: Math.min(limits1.xmin, limits2.xmin),
  48.         ymax: Math.max(limits1.ymax, limits2.ymax),
  49.         ymin: Math.min(limits1.ymin, limits2.ymin)
  50.     }
  51. }
  52.  
  53. function drawMap(limits) {
  54.     let map = [];
  55.     let ylength = Math.abs(limits.ymin - limits.ymax - 1);
  56.     let xlength = Math.abs(limits.xmin - limits.xmax - 1);
  57.     let xline = [];
  58.     for (i = 0; i < xlength; i++) {
  59.         xline.push('0');
  60.     }
  61.     for (i = 0; i < ylength; i++) {
  62.         map.push(xline.slice(0));
  63.     }
  64.     map[limits.ymax][limits.xmin] = 'W';
  65.     for (i = 0; i < map.length; i++) {
  66.         console.log(map[i].join(''))
  67.     }
  68.     return map;
  69. }
  70.  
  71. fsPromises.readFile('/Users/Elture/Desktop/projects/puzzles/puzzle4input.txt', 'utf-8')
  72. .then((string) => {
  73.     let firstCable = string.split('\r\n')[0].split(',');
  74.     let secondCable = string.split('\r\n')[1].split(',');
  75.     let limitsFirst = getLimits(firstCable);
  76.     let limitsSecond = getLimits(secondCable);
  77.     let fullLimits = combineLimits(limitsFirst, limitsSecond);
  78.     drawMap(fullLimits)
  79. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement