this post was submitted on 01 Dec 2023
8 points (100.0% liked)

Advent of Code

283 readers
1 users here now

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

https://adventofcode.com

founded 1 year ago
MODERATORS
8
Day 1 solutions (adventofcode.com)
submitted 11 months ago* (last edited 11 months ago) by [email protected] to c/[email protected]
 

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.

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 4 points 11 months ago* (last edited 11 months 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;