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

Advent of Code

1 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
2
Day 1 solutions (adventofcode.com)
submitted 10 months ago* (last edited 10 months ago) by mykl@lemmy.world to c/adventofcode@lemmy.world
 

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
[–] Andy@programming.dev 2 points 10 months ago* (last edited 10 months ago)

I'm not really happy with the repetition I have, but here's my Factor solution:

Here it is on GitHub with comments and imports.

: part1 ( -- )
  "vocab:aoc-2023/day01/input.txt" utf8 file-lines
  [
    [ [ digit? ] find nip ]
    [ [ digit? ] find-last nip ] bi
    2array string>number
  ] map-sum .
;

MEMO: digit-words ( -- name-char-assoc )
  [ "123456789" [ dup char>name "-" split1 nip ,, ] each ] H{ } make
;

: first-digit-char ( str -- num-char/f i/f )
  [ digit? ] find swap
;

: last-digit-char ( str -- num-char/f i/f )
  [ digit? ] find-last swap
;

: first-digit-word ( str -- num-char/f )
  [
    digit-words keys [
      2dup subseq-index
      dup [
        [ digit-words at ] dip
        ,,
      ] [ 2drop ] if
    ] each drop                           !
  ] H{ } make
  [ f ] [
    sort-keys first last
  ] if-assoc-empty
;

: last-digit-word ( str -- num-char/f )
  reverse
  [
    digit-words keys [
      reverse
      2dup subseq-index
      dup [
        [ reverse digit-words at ] dip
        ,,
      ] [ 2drop ] if
    ] each drop                           !
  ] H{ } make
  [ f ] [
    sort-keys first last
  ] if-assoc-empty
;

: first-digit ( str -- num-char )
  dup first-digit-char dup [
    pick 2dup swap head nip
    first-digit-word dup [
      [ 2drop ] dip
    ] [ 2drop ] if
    nip
  ] [
    2drop first-digit-word
  ] if
;

: last-digit ( str -- num-char )
  dup last-digit-char dup [
    pick 2dup swap 1 + tail nip
    last-digit-word dup [
      [ 2drop ] dip
    ] [ 2drop ] if
    nip
  ] [
    2drop last-digit-word
  ] if
;

: part2 ( -- )
  "vocab:aoc-2023/day01/input.txt" utf8 file-lines
  [ [ first-digit ] [ last-digit ] bi 2array string>number ] map-sum .
;