ShareMyScreen/AdventOfCode/2023/01/Trebuchet/rdm

From J Wiki
Jump to navigation Jump to search

Dealing with the input is a large part of the advent of code problems, especially in the early days of December.

For day 1, I define a sample which I use for testing, and also have downloaded a file which I wish to retain for later. I don't know if I'll be doing the full set of problems yet - that's going to depend on how I feel about problems in the last week of this advent. But, it can be convenient to refer back to a previous day's data set without having to download it afresh.

Thus:

1sample=: {{)n
21abc2
3pqr3stu8vwx
4a1b2c3d4e5f
5treb7uchet
6}}
7
8day1=: ([ fwrite&'2003-day1.txt') fread '~/Downloads/input.txt'

(I'll need to remember to pull out that fwrite before I overwrite the day1 file with a later day's input.)

Here, for each line of input data, I want the first and last digit which appears on that line, interpreted as a two digit number. Apparently, no zeros allowed, but that hasn't been explicitly stated, yet, as far as I saw.

10calib=: {{ ". ({.,{:) y ([-.-.)'0123456789' }};._2
11part1=: +/@calib

That gives me:

   calib sample
12 38 15 77
   part1 sample
142

Using some function;._2 to parse lines is pretty common for advent of code puzzles. Sometimes J's cutLF is more convenient, but ;._2 is nice enough here.

Part 2 introduces a new sample data set, and where some of the digits have names which are spelled out, and some of those names overlap with the names of other digits. I can use rplc to replace names with digits, but I need to allow for the overlap. The approach I finally settled on was this:

13sample2=: {{)n
14two1nine
15eightwothree
16abcone2threexyz
17xtwone3four
184nineeightseven2
19zoneight234
207pqrstsixteen
21}}
22
23fixup=: rplc&(;:'one o1e two t2o three t3e four f4r five f5e six s6x seven s7n eight e8t nine n9e')^:2
24part2=: part1@fixup

This gives me:

   fixup sample2
t2o1n9e
e8t2ot3e
abco1e2t3exyz
xt2o1e3f4r
4n9ee8ts7n2
zo1e8t234
7pqrsts6xteen

   calib fixup sample2
29 83 13 24 42 14 76
   part2 sample2
281

And, of course for my actual puzzle results I used the results from part1 day1 and part2 day1

(Also, for people looking at line numbers on my code here... lines 9 and 12 of my implementation were blank.)

day 2