Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const cloneDeep = require('lodash.clonedeep');
  2. const fs = require('fs');
  3.  
  4. function solve() {
  5.     const contents = fs.readFileSync('./input2.txt', 'utf8');
  6.     let array = contents.split("\r\n").map(x => x.split('')), directions = calculateDirections(50), maxCount = -Infinity;
  7.  
  8.     for (let i = 0; i < array.length; i++) {
  9.         for (let j = 0; j < array[i].length; j++) {
  10.             if (array[i][j] !== '#') continue;
  11.             let tmp = cloneDeep(array);
  12.             for (let direction of directions) {
  13.                 let x = i, y = j, foundAsteroid = false;
  14.                 while (true) {
  15.                     [x,y] = [x+direction[0], y+direction[1]];
  16.                     if (x >= array.length || y >= array[i].length || x < 0 || y < 0) {
  17.                         break;
  18.                     }
  19.                     if (tmp[x][y] === '#') {
  20.                         if (foundAsteroid) {
  21.                             tmp[x][y] = '-';
  22.                         } else {
  23.                             foundAsteroid = true;
  24.                         }
  25.                     }
  26.                 }
  27.             }
  28.             tmp[i][j] = 'S';
  29.             let counter = countAsteroids(tmp);
  30.             if(counter>maxCount){
  31.                 maxCount = counter;
  32.             }
  33.         }
  34.  
  35.     }
  36.     return maxCount;
  37. }
  38.  
  39. countAsteroids = (arr) => {
  40.     let counter = 0;
  41.     for (let i = 0; i < arr.length; i++) {
  42.         for (let j = 0; j < arr[i].length; j++) {
  43.             if (arr[i][j] === '#') {
  44.                 counter++;
  45.             }
  46.         }
  47.     }
  48.     return counter;
  49. };
  50.  
  51. calculateDirections = (size) => {
  52.     let directions = [];
  53.     for(let i=0; i<size; i++){
  54.         for(let j=0; j<size; j++){
  55.             if(i!==0 || j!==0)
  56.                 directions.push([i,j]);
  57.             if(i!==0)
  58.                 directions.push([-i, j]);
  59.             if(j!==0)
  60.                 directions.push([i, -j]);
  61.             if(i!==0 && j!==0)
  62.                 directions.push([-i,-j]);
  63.         }
  64.     }
  65.     return directions;
  66. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement