Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Given a grid of (real) trees of different heights
- /// 1) Find how many are visible from any edge
- /// 2) Find the best view from any trees (= product of distances)
- // ignore_for_file: unused_import
- import 'dart:io';
- import 'package:collection/collection.dart';
- import 'package:more/more.dart';
- // Add an offset of 1 to every tree so that 0-height tree work for this hack.
- List<List<int>> readTrees(List<String> lines) => lines
- .map((e) => e.split('').map((e) => int.parse(e) + 1).toList())
- .toList();
- part1(List<String> lines) {
- var trees = readTrees(lines);
- // helper function
- int checkHeight(row, col, targetHeight) {
- if (trees[row][col].abs() > targetHeight) {
- targetHeight = trees[row][col].abs();
- trees[row][col] = -targetHeight; // <-- means visible!
- }
- return targetHeight;
- }
- var nCols = trees.first.length, nRows = trees.length;
- for (var row in 0.to(nRows)) {
- 0.to(nCols).fold(-99, (s, t) => checkHeight(row, t, s));
- 0.to(nCols).reversed.fold(-99, (s, t) => checkHeight(row, t, s));
- }
- for (var col in 0.to(nCols)) {
- 0.to(nRows).fold(-99, (s, t) => checkHeight(t, col, s));
- 0.to(nRows).reversed.fold(-99, (s, t) => checkHeight(t, col, s));
- }
- return trees.flattened.where((e) => e < 1).length;
- }
- // Part 2
- var dirs = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0]
- ];
- List<int> viewsFromTree(List<List<int>> trees, List<int> rc) {
- var row = rc[0], col = rc[1];
- inBounds(r, c) =>
- r >= 0 && r < trees.length && c >= 0 && c < trees.first.length;
- var high = trees[row][col];
- var vals = <int>[];
- for (var dir in dirs) {
- var hr = row, hc = col;
- var val = 0;
- while (true) {
- hr += dir[0];
- hc += dir[1];
- if (!inBounds(hr, hc)) break;
- val += 1;
- if (trees[hr][hc] >= high) break;
- }
- vals.add(val);
- }
- return vals;
- }
- part2(List<String> lines) {
- var trees = readTrees(lines);
- var rowColPairs = [
- for (var row in 0.to(trees.length))
- for (var col in 0.to(trees.first.length)) [row, col]
- ];
- return rowColPairs.fold(
- -1,
- (sofar, rc) =>
- [sofar, viewsFromTree(trees, rc).reduce((s, t) => s * t)].max);
- }
- void main(List<String> args) {
- var lines = File('data/data08_01.txt').readAsLinesSync();
- var t = DateTime.now();
- print(part1(lines));
- print(part2(lines));
- print('${DateTime.now().difference(t).inMicroseconds} microseconds');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement