Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:math';
- import 'package:petitparser/petitparser.dart';
- import 'advent2020.dart';
- import 'package:advent2020/eulib.dart' as eulib;
- void main() {
- day24a();
- day24b();
- }
- void day24a() {
- var p = buildParser();
- flipped = <Point, bool>{};
- var lines = readLinesFromFile('data/day24_data.txt');
- for (var l in lines) {
- CURR = Point(0, 0);
- p.parse(l);
- flipped[CURR] = !(flipped[CURR] ?? false);
- }
- assert(flipped.values.where((e) => e).length == 254);
- }
- void day24b() {
- var p = buildParser();
- flipped = <Point, bool>{};
- var lines = readLinesFromFile('data/day24_data.txt');
- for (var l in lines) {
- CURR = Point(0, 0);
- p.parse(l);
- flipped[CURR] = !(flipped[CURR] ?? false);
- }
- // Actual test.
- for (var _ in eulib.range(0, 100)) {
- flipped = life(flipped);
- }
- assert(flipped.values.where((e) => e).length == 3697);
- }
- // x y = bottom left.
- /*
- Two overlapping grids
- (1,3)---|---(3,3)------
- | | |
- (0,2)-------(2,2)-------(4,2)--
- | | |
- (1,1)---|---(3,1)-------
- */
- var dirs = {
- 'ne': Point(1, 1),
- 'se': Point(1, -1),
- 'sw': Point(-1, -1),
- 'nw': Point(-1, 1),
- 'e': Point(2, 0),
- 'w': Point(-2, 0),
- };
- Point CURR;
- void move(String dir) => CURR += dirs[dir];
- Parser buildParser() {
- var ne = (char('n') & char('e')).map((arr) => move('ne'));
- var se = (char('s') & char('e')).map((arr) => move('se'));
- var sw = (char('s') & char('w')).map((arr) => move('sw'));
- var nw = (char('n') & char('w')).map((arr) => move('nw'));
- var e = (char('e')).map((arr) => move('e'));
- var w = (char('w')).map((arr) => move('w'));
- var exp = (ne | se | sw | nw | e | w).plus();
- var b = ExpressionBuilder();
- b.group().primitive(exp);
- var rp = b.build().end();
- return rp;
- }
- Map<Point, bool> flipped;
- Map<Point, bool> life(Map<Point, bool> current) {
- // Expand borders to include all needed whites.
- for (var p in current.keys.toList()) {
- for (var d in dirs.values) {
- current.putIfAbsent(p + d, () => false);
- }
- }
- // Copy current state into future state.
- var next = Map<Point, bool>.fromEntries(current.entries);
- for (var p in current.keys) {
- // Count flipped (=black) neighbours
- var n = dirs.values.where((e) => current[p + e] ?? false).length;
- // Are we on a black tile?
- if (current[p]) {
- if (n == 0 || n > 2) {
- next[p] = false;
- }
- // White.
- } else {
- if (n == 2) {
- next[p] = true;
- }
- }
- }
- return next;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement