Day 13: Point of Incidence

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/ , pastebin, or github (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


🔒 Thread is locked until there’s at least 100 2 star entries on the global leaderboard

🔓 Unlocked

  • @mykl
    link
    36 months ago

    Dart

    Just banging strings together again. Simple enough once I understood that the original reflection may also be valid after desmudging. I don’t know if we were supposed to do something clever for part two, but my part 1 was fast enough that I could just try every possible smudge location and part 2 still ran in 80ms

    bool reflectsH(int m, List p) => p.every((l) {
          var l1 = l.take(m).toList().reversed.join('');
          var l2 = l.skip(m);
          var len = min(l1.length, l2.length);
          return l1.take(len) == l2.take(len);
        });
    
    bool reflectsV(int m, List p) {
      var l1 = p.take(m).toList().reversed.toList();
      var l2 = p.skip(m).toList();
      var len = min(l1.length, l2.length);
      return 0.to(len).every((ix) => l1[ix] == l2[ix]);
    }
    
    int findReflection(List p, {int butNot = -1}) {
      var mirrors = 1
          .to(p.first.length)
          .where((m) => reflectsH(m, p))
          .toSet()
          .difference({butNot});
      if (mirrors.length == 1) return mirrors.first;
    
      mirrors = 1
          .to(p.length)
          .where((m) => reflectsV(m, p))
          .toSet()
          .difference({butNot ~/ 100});
      if (mirrors.length == 1) return 100 * mirrors.first;
    
      return -1; //never
    }
    
    int findSecondReflection(List p) {
      var origMatch = findReflection(p);
      for (var r in 0.to(p.length)) {
        for (var c in 0.to(p.first.length)) {
          var pp = p.toList();
          var cells = pp[r].split('');
          cells[c] = (cells[c] == '#') ? '.' : '#';
          pp[r] = cells.join();
          var newMatch = findReflection(pp, butNot: origMatch);
          if (newMatch > -1) return newMatch;
        }
      }
      return -1; // never
    }
    
    Iterable> parse(List lines) => lines
        .splitBefore((e) => e.isEmpty)
        .map((e) => e.first.isEmpty ? e.skip(1).toList() : e);
    
    part1(lines) => parse(lines).map(findReflection).sum;
    
    part2(lines) => parse(lines).map(findSecondReflection).sum;