Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Load the textfile into a 2D array
- const fs = require('fs');
- const text = fs.readFileSync(__dirname + "/test.txt", 'utf8');
- const lines = text.split('\r\n');
- const grid = lines.map(line => line.split('').map(Number));
- // Iterate through the array and check if each tree is visible
- let visibleTrees = 0;
- for (let i = 0; i < grid.length; i++) {
- for (let j = 0; j < grid[i].length; j++) {
- // Check if the current tree is visible from the top
- if (i > 0) {
- let isVisible = true;
- for (let k = 0; k < i; k++) {
- if (grid[k][j] >= grid[i][j]) {
- isVisible = false;
- break;
- }
- }
- if (isVisible) visibleTrees++;
- }
- // Check if the current tree is visible from the bottom
- if (i < grid.length - 1) {
- let isVisible = true;
- for (let k = i + 1; k < grid.length; k++) {
- if (grid[k][j] >= grid[i][j]) {
- isVisible = false;
- break;
- }
- }
- if (isVisible) visibleTrees++;
- }
- // Check if the current tree is visible from the left
- if (j > 0) {
- let isVisible = true;
- for (let k = 0; k < j; k++) {
- if (grid[i][k] >= grid[i][j]) {
- isVisible = false;
- break;
- }
- }
- if (isVisible) visibleTrees++;
- }
- // Check if the current tree is visible from the right
- if (j < grid[i].length - 1) {
- let isVisible = true;
- for (let k = j + 1; k < grid[i].length; k++) {
- if (grid[i][k] >= grid[i][j]) {
- isVisible = false;
- break;
- }
- }
- if (isVisible) visibleTrees++;
- }
- }
- }
- // Output the total number of visible trees
- console.log(visibleTrees);
Advertisement
Add Comment
Please, Sign In to add comment