mosredna

AoC 2022 day 8 ( CHATGPT wrong answer)

Dec 8th, 2022
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Load the textfile into a 2D array
  2. const fs = require('fs');
  3. const text = fs.readFileSync(__dirname + "/test.txt", 'utf8');
  4. const lines = text.split('\r\n');
  5. const grid = lines.map(line => line.split('').map(Number));
  6.  
  7. // Iterate through the array and check if each tree is visible
  8. let visibleTrees = 0;
  9. for (let i = 0; i < grid.length; i++) {
  10.     for (let j = 0; j < grid[i].length; j++) {
  11.         // Check if the current tree is visible from the top
  12.         if (i > 0) {
  13.             let isVisible = true;
  14.             for (let k = 0; k < i; k++) {
  15.                 if (grid[k][j] >= grid[i][j]) {
  16.                     isVisible = false;
  17.                     break;
  18.                 }
  19.             }
  20.             if (isVisible) visibleTrees++;
  21.         }
  22.         // Check if the current tree is visible from the bottom
  23.         if (i < grid.length - 1) {
  24.             let isVisible = true;
  25.             for (let k = i + 1; k < grid.length; k++) {
  26.                 if (grid[k][j] >= grid[i][j]) {
  27.                     isVisible = false;
  28.                     break;
  29.                 }
  30.             }
  31.             if (isVisible) visibleTrees++;
  32.         }
  33.         // Check if the current tree is visible from the left
  34.         if (j > 0) {
  35.             let isVisible = true;
  36.             for (let k = 0; k < j; k++) {
  37.                 if (grid[i][k] >= grid[i][j]) {
  38.                     isVisible = false;
  39.                     break;
  40.                 }
  41.             }
  42.             if (isVisible) visibleTrees++;
  43.         }
  44.         // Check if the current tree is visible from the right
  45.         if (j < grid[i].length - 1) {
  46.             let isVisible = true;
  47.             for (let k = j + 1; k < grid[i].length; k++) {
  48.                 if (grid[i][k] >= grid[i][j]) {
  49.                     isVisible = false;
  50.                     break;
  51.                 }
  52.             }
  53.             if (isVisible) visibleTrees++;
  54.         }
  55.     }
  56. }
  57.  
  58. // Output the total number of visible trees
  59. console.log(visibleTrees);
Advertisement
Add Comment
Please, Sign In to add comment