How was day one for everyone? I was surprised at how tricky it was to get the right answer for part two. Not the usual easy start I’ve seen in the past. I’d be interested to see any solutions here.

  • mykl@lemmy.worldOPM
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    1 year ago

    Dart solution

    Here’s my solution to start the ball rolling. In the end I incorporated my part 1 answer into the part 2 logic, and golfed the code quite a lot.

    import 'package:collection/collection.dart';
    
    var ds = '0123456789'.split('');
    var wds = 'one two three four five six seven eight nine'.split(' ');
    
    int s2d(String s) => s.length == 1 ? int.parse(s) : wds.indexOf(s) + 1;
    
    int value(String s, List digits) {
      var firsts = {for (var e in digits) s.indexOf(e): e}..remove(-1);
      var lasts = {for (var e in digits) s.lastIndexOf(e): e}..remove(-1);
      return s2d(firsts[firsts.keys.min]) * 10 + s2d(lasts[lasts.keys.max]);
    }
    
    part1(List lines) => lines.map((e) => value(e, ds)).sum;
    
    part2(List lines) => lines.map((e) => value(e, ds + wds)).sum;