main.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const fs = require('fs');
  2. const readline = require('readline');
  3. function isVisible(map, posX, posY) {
  4. let i =1;
  5. let visibility = [ true, true, true, true ];
  6. let maxDist = [ posX, map.length -posX -1, posY, map[0].length -posY -1 ];
  7. let cross = [];
  8. do {
  9. cross = [ map[posX-i]?.[posY], map[posX+i]?.[posY], map[posX]?.[posY-i], map[posX]?.[posY+i] ];
  10. cross.forEach((tree, index) => {
  11. if (tree && tree.height >= map[posX][posY].height && visibility[index]) {
  12. visibility[index] = false;
  13. maxDist[index] = i;
  14. }
  15. });
  16. ++i;
  17. }
  18. while (!cross.every(x => !x) && !visibility.every(i => !i));
  19. map[posX][posY].visible = visibility.filter(i => !!i).length;
  20. map[posX][posY].maxDist = maxDist.reduce((acc, i) => acc ? acc * i : i);
  21. }
  22. function getColor(height) {
  23. return "\033[" +[39, 32, 32, 92, 33, 93, 93, 91, 31, 31][height] +'m';
  24. }
  25. async function main() {
  26. let lines = [];
  27. let visible = [];
  28. for await (let line of readline.createInterface({ input: process.stdin })) {
  29. lines.push(line.split("").map(i => { return { height: parseInt(i), visible: 0, maxDist: 0 };}));
  30. }
  31. for (let i =0; i < lines.length; ++i)
  32. for (let j =0; j < lines[i].length; ++j)
  33. isVisible(lines, i, j);
  34. for (let i of lines) {
  35. let buf = "";
  36. for (let j of i)
  37. buf += getColor(j.height) +'x';
  38. buf += getColor(0);
  39. console.log(buf);
  40. }
  41. console.log("Number of visible trees: ", lines.reduce((acc, i) => acc ? acc.concat(i) : i).filter(i => i.visible).length);
  42. console.log("Max scenic score: ", Math.max(...lines.reduce((acc, i) => acc ? acc.concat(i) : i).map(i => i.maxDist)));
  43. };
  44. (main());