Day 3: Gear Ratios


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 11 minutes

  • @mykl
    link
    2
    edit-2
    1 year ago

    Dart Solution

    Holy moley, if this year is intended to be impervious to AI solution, it’s also working pretty well as a filter to this paltry Human Intelligence.

    Find interesting symbols, look around for digits, and expand these into numbers. A dirty hacky solution leaning on a re-used Grid class. Not recommended.

    late ListGrid grid;
    
    Index look(Index ix, Index dir) {
      var here = ix;
      var next = here + dir;
      while (grid.isInBounds(next) && '1234567890'.contains(grid.at(next))) {
        here = next;
        next = here + dir;
      }
      return here;
    }
    
    /// Return start and end indices of a number at a point.
    (Index, Index) expandNumber(Index ix) =>
        (look(ix, Grid.dirs['L']!), look(ix, Grid.dirs['R']!));
    
    int parseNumber((Index, Index) e) => int.parse([
          for (var i = e.$1; i != e.$2 + Grid.dirs['R']!; i += Grid.dirs['R']!)
            grid.at(i)
        ].join());
    
    /// Return de-duplicated positions of all numbers near the given symbols.
    nearSymbols(Set syms) => [
          for (var ix in grid.indexes.where((i) => syms.contains(grid.at(i))))
            {
              for (var n in grid
                  .near8(ix)
                  .where((n) => ('1234567890'.contains(grid.at(n)))))
                expandNumber(n)
            }.toList()
        ];
    
    part1(List lines) {
      grid = ListGrid([for (var e in lines) e.split('')]);
      var syms = lines
          .join('')
          .split('')
          .toSet()
          .difference('0123456789.'.split('').toSet());
      // Find distinct number locations near symbols and sum them.
      return {
        for (var ns in nearSymbols(syms))
          for (var n in ns) n
      }.map(parseNumber).sum;
    }
    
    part2(List lines) {
      grid = ListGrid([for (var e in lines) e.split('')]);
      // Look for _pairs_ of numbers near '*' and multiply them.
      var products = [
        for (var ns in nearSymbols({'*'}).where((e) => e.length == 2))
          ns.map(parseNumber).reduce((s, t) => s * t)
      ];
      return products.sum;
    }