Advertisement
mykdavies

AOC2021 Day24

Dec 24th, 2021 (edited)
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.29 KB | None | 0 0
  1. ///INTERPRET SOME MACHINE CODE.
  2. // We want to build a pool of states, and understand which lead where.
  3. // Once we have these, we want to find the most (then least) *expensive* route where
  4. // at each step cost = (10* cost sofar) + next digit. (ie number made by
  5. // joining all digits so far).
  6.  
  7. import 'dart:io';
  8.  
  9. import 'package:more/more.dart';
  10. import 'package:collection/collection.dart';
  11.  
  12. late List<List<int>> params;
  13. buildParams(List<String> lines) {
  14.   var sections = lines.splitBefore((e) => e.startsWith('inp'));
  15.   params = sections
  16.       .map((s) => [
  17.             for (var i in [4, 5, 15]) int.parse(s[i].split(' ')[2])
  18.           ])
  19.       .toList();
  20. }
  21.  
  22. int buildNodes([bool mn = false]) {
  23.   // `z` is the only part of state that actually gets used.
  24.   // build a map of current `z`s and their best(highest/lowest) costs.
  25.   Map<int, int> queue = {0: 0};
  26.  
  27.   for (var i in 0.to(14)) {
  28.     print('next section - queue ${queue.length}');
  29.     var nextMap = <int, int>{};
  30.     for (var e in queue.entries) {
  31.       var current = e.key;
  32.       var c0 = e.value * 10;
  33.       for (var d in 1.to(10)) {
  34.         var c = c0 + d;
  35.         var endState = runSectionNumber(i, d, current);
  36.  
  37.         // Only keep track of the identical states that were most
  38.         // expensive to create.
  39.         if (!mn && (nextMap[endState] ?? 0) < c) {
  40.           nextMap[endState] = c;
  41.         } else {
  42.           if ((nextMap[endState] ?? maxSafeInteger) > c) {
  43.             nextMap[endState] = c;
  44.           }
  45.         }
  46.       }
  47.     }
  48.     queue = nextMap;
  49.   }
  50.   // We now have a list of final state Nodes.
  51.   var good = queue.keys.where((e) => e == 0);
  52.   var cost =
  53.       mn ? good.map((e) => queue[e]).min() : good.map((e) => queue[e]).max();
  54.   return cost!;
  55. }
  56.  
  57. int runSectionNumber(int sn, int digit, int z) {
  58.   int w = digit;
  59.   List<int> p = params[sn];
  60.   var x = z % 26;
  61.   z = z ~/ p[0];
  62.   x += p[1];
  63.   x = (x != w) ? 1 : 0;
  64.   var y = x == 1 ? 26 : 1;
  65.   z *= y;
  66.   y = w + p[2];
  67.   y *= x;
  68.   z += y;
  69.   return z;
  70. }
  71.  
  72. main() {
  73.   var lines = File('data/data24_01.txt').readAsLinesSync();
  74.   var t = DateTime.now();
  75.   buildParams(lines);
  76.   print(buildNodes()); // 93499629698999
  77.   print(buildNodes(true)); // 11164118121471
  78.   print('${DateTime.now().difference(t).inMilliseconds} milliseconds');
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement