Welcome everyone to the 2023 advent of code! Thank you all for stopping by and participating in it in programming.dev whether youre new to the event or doing it again.
This is an unofficial community for the event as no official spot exists on lemmy but ill be running it as best I can with Sigmatics modding as well. Ill be running a solution megathread every day where you can share solutions with other participants to compare your answers and to see the things other people come up with
Day 1: Trebuchet?!
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/ or pastebin (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
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots
🔓 Edit: Post has been unlocked after 6 minutes
Python
Questions and feedback welcome!
import re from .solver import Solver class Day01(Solver): def __init__(self): super().__init__(1) self.lines = [] def presolve(self, input: str): self.lines = input.rstrip().split('\n') def solve_first_star(self): numbers = [] for line in self.lines: digits = [ch for ch in line if ch.isdigit()] numbers.append(int(digits[0] + digits[-1])) return sum(numbers) def solve_second_star(self): numbers = [] digit_map = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "zero": 0, } for i in range(10): digit_map[str(i)] = i for line in self.lines: digits = [digit_map[digit] for digit in re.findall( "(?=(one|two|three|four|five|six|seven|eight|nine|[0-9]))", line)] numbers.append(digits[0]*10 + digits[-1]) return sum(numbers)
[Language: C#]
This isn’t the most performant or elegant, it’s the first one that worked. I have 3 kids and a full time job. If I get through any of these, it’ll be first pass through and first try that gets the correct answer.
Part 1 was very easy, just iterated the string checking if the char was a digit. Ditto for the last, by reversing the string. Part 2 was also not super hard, I settled on re-using the iterative approach, checking each string lookup value first (on a substring of the current char), and if the current char isn’t the start of a word, then checking if the char was a digit. Getting the last number required reversing the string and the lookup map.
Part 1:
var list = new List((await File.ReadAllLinesAsync(@".\Day 1\PuzzleInput.txt"))); int total = 0; foreach (var item in list) { //forward string digit1 = string.Empty; string digit2 = string.Empty; foreach (var c in item) { if ((int)c >= 48 && (int)c <= 57) { digit1 += c; break; } } //reverse foreach (var c in item.Reverse()) { if ((int)c >= 48 && (int)c <= 57) { digit2 += c; break; } } total += Int32.Parse(digit1 +digit2); } Console.WriteLine(total);
Part 2:
var list = new List((await File.ReadAllLinesAsync(@".\Day 1\PuzzleInput.txt"))); var numbers = new Dictionary() { {"one" , 1} ,{"two" , 2} ,{"three" , 3} ,{"four" , 4} ,{"five" , 5} ,{"six" , 6} ,{"seven" , 7} ,{"eight" , 8} , {"nine" , 9 } }; int total = 0; string digit1 = string.Empty; string digit2 = string.Empty; foreach (var item in list) { //forward digit1 = getDigit(item, numbers); digit2 = getDigit(new string(item.Reverse().ToArray()), numbers.ToDictionary(k => new string(k.Key.Reverse().ToArray()), k => k.Value)); total += Int32.Parse(digit1 + digit2); } Console.WriteLine(total); string getDigit(string item, Dictionary numbers) { int index = 0; int digit = 0; foreach (var c in item) { var sub = item.AsSpan(index++); foreach(var n in numbers) { if (sub.StartsWith(n.Key)) { digit = n.Value; goto end; } } if ((int)c >= 48 && (int)c <= 57) { digit = ((int)c) - 48; break; } } end: return digit.ToString(); }
I’m a bit late to the party. I forgot about this.
Anyways, my (lazy) C solutions: https://git.sr.ht/~aidenisik/aoc23/tree/master/item/day1
Java
My take on a modern Java solution (parts 1 & 2).
spoiler
package thtroyer.day1; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Day1 { record Match(int index, String name, int value) { } Map numbers = Map.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9); /** * Takes in all lines, returns summed answer */ public int getCalibrationValue(String... lines) { return Arrays.stream(lines) .map(this::getCalibrationValue) .map(Integer::parseInt) .reduce(0, Integer::sum); } /** * Takes a single line and returns the value for that line, * which is the first and last number (numerical or text). */ protected String getCalibrationValue(String line) { var matches = Stream.concat( findAllNumberStrings(line).stream(), findAllNumerics(line).stream() ).sorted(Comparator.comparingInt(Match::index)) .toList(); return "" + matches.getFirst().value() + matches.getLast().value(); } /** * Find all the strings of written numbers (e.g. "one") * * @return List of Matches */ private List findAllNumberStrings(String line) { return IntStream.range(0, line.length()) .boxed() .map(i -> findAMatchAtIndex(line, i)) .filter(Optional::isPresent) .map(Optional::get) .sorted(Comparator.comparingInt(Match::index)) .toList(); } private Optional findAMatchAtIndex(String line, int index) { return numbers.entrySet().stream() .filter(n -> line.indexOf(n.getKey(), index) == index) .map(n -> new Match(index, n.getKey(), n.getValue())) .findAny(); } /** * Find all the strings of digits (e.g. "1") * * @return List of Matches */ private List findAllNumerics(String line) { return IntStream.range(0, line.length()) .boxed() .filter(i -> Character.isDigit(line.charAt(i))) .map(i -> new Match(i, null, Integer.parseInt(line.substring(i, i + 1)))) .toList(); } public static void main(String[] args) { System.out.println(new Day1().getCalibrationValue(args)); } }
I feel ok about part 1, and just terrible about part 2.
day01.factor
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 . ;
APL
spoiler
args ← {1↓⍵/⍨∨\⍵∊⊂'--'} ⎕ARG inputs ← ⎕FIO[49]¨ args words ← 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' 'nine' digits ← '123456789' part1 ← {↑↑+/{(10×↑⍵)+¯1↑⍵}¨{⍵~0}¨+⊃(⍳9)+.×digits∘.⍷⍵} "Part 1: ", part1¨ inputs part2 ← {↑↑+/{(10×↑⍵)+¯1↑⍵}¨{⍵~0}¨+⊃(⍳9)+.×(words∘.⍷⍵)+digits∘.⍷⍵} "Part 2: ", part2¨ inputs )OFF
[Language: Lean4]
I’ll only post the actual parsing and solution. I have written some helpers which are in other files, as is the main function. For the full code, please see my github repo.
Part 2 is a bit ugly, but I’m still new to Lean4, and writing it this way (structural recursion) just worked without a proof or termination.
Solution
def parse (input : String) : Option $ List String := some $ input.split Char.isWhitespace |> List.filter (not ∘ String.isEmpty) def part1 (instructions : List String) : Option Nat := let firstLast := λ (o : Option Nat × Option Nat) (c : Char) ↦ let digit := match c with | '0' => some 0 | '1' => some 1 | '2' => some 2 | '3' => some 3 | '4' => some 4 | '5' => some 5 | '6' => some 6 | '7' => some 7 | '8' => some 8 | '9' => some 9 | _ => none if let some digit := digit then match o.fst with | none => (some digit, some digit) | some _ => (o.fst, some digit) else o let scanLine := λ (l : String) ↦ l.foldl firstLast (none, none) let numbers := instructions.mapM ((uncurry Option.zip) ∘ scanLine) let numbers := numbers.map λ l ↦ l.map λ (a, b) ↦ 10*a + b numbers.map (List.foldl (.+.) 0) def part2 (instructions : List String) : Option Nat := -- once I know how to prove stuff propery, I'm going to improve this. Maybe. let instructions := instructions.map String.toList let updateState := λ (o : Option Nat × Option Nat) (n : Nat) ↦ match o.fst with | none => (some n, some n) | some _ => (o.fst, some n) let extract_digit := λ (o : Option Nat × Option Nat) (l : List Char) ↦ match l with | '0' :: _ | 'z' :: 'e' :: 'r' :: 'o' :: _ => (updateState o 0) | '1' :: _ | 'o' :: 'n' :: 'e' :: _ => (updateState o 1) | '2' :: _ | 't' :: 'w' :: 'o' :: _ => (updateState o 2) | '3' :: _ | 't' :: 'h' :: 'r' :: 'e' :: 'e' :: _ => (updateState o 3) | '4' :: _ | 'f' :: 'o' :: 'u' :: 'r' :: _ => (updateState o 4) | '5' :: _ | 'f' :: 'i' :: 'v' :: 'e' :: _ => (updateState o 5) | '6' :: _ | 's' :: 'i' :: 'x' :: _ => (updateState o 6) | '7' :: _ | 's' :: 'e' :: 'v' :: 'e' :: 'n' :: _ => (updateState o 7) | '8' :: _ | 'e' :: 'i' :: 'g' :: 'h' :: 't' :: _ => (updateState o 8) | '9' :: _ | 'n' :: 'i' :: 'n' :: 'e' :: _ => (updateState o 9) | _ => o let rec firstLast := λ (o : Option Nat × Option Nat) (l : List Char) ↦ match l with | [] => o | _ :: cs => firstLast (extract_digit o l) cs let scanLine := λ (l : List Char) ↦ firstLast (none, none) l let numbers := instructions.mapM ((uncurry Option.zip) ∘ scanLine) let numbers := numbers.map λ l ↦ l.map λ (a, b) ↦ 10*a + b numbers.map (List.foldl (.+.) 0)
I think I found a decently short solution for part 2 in python:
DIGITS = { 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', } def find_digit(word: str) -> str: for digit, value in DIGITS.items(): if word.startswith(digit): return value if word.startswith(value): return value return '' total = 0 for line in puzzle.split('\n'): digits = [ digit for i in range(len(line)) if (digit := find_digit(line[i:])) ] total += int(digits[0] + digits[-1]) print(total)
Looks very elegant! I’m having trouble understanding how this finds digit “words” from the end of the line though, as they should be spelled backwards IIRC? I.e.
eno
,owt
,eerht
It simply finds all possible digits and then locates the last one through the reverse indexing. It’s not efficient because there’s no shortcircuiting, but there’s no need to search the strings backwards, which is nice. Python’s startswith method is also hiding a lot of that other implementations have done explicitly.
I wanted to see if it was possible to do part 1 in a single line of Python:
print(sum([(([int(i) for i in line if i.isdigit()][0]) * 10 + [int(i) for i in line if i.isdigit()][-1]) for line in open("input.txt")]))
[Rust] 11157/6740
use std::fs; const m: [(&str, u32); 10] = [ ("zero", 0), ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5), ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9) ]; fn main() { let s = fs::read_to_string("data/input.txt").unwrap(); let mut u = 0; for l in s.lines() { let mut h = l.chars(); let mut f = 0; let mut a = 0; for n in 0..l.len() { let u = h.next().unwrap(); match u.is_numeric() { true => { let v = u.to_digit(10).unwrap(); if f == 0 { f = v; } a = v; }, _ => { for (t, v) in m { if l[n..].starts_with(t) { if f == 0 { f = v; } a = v; } } }, } } u += f * 10 + a; } println!("Sum: {}", u); }
Ive been trying to learn rust for like a month now and I figured I’d try aoc with rust instead of typescript. Your solution is way better than mine and also pretty incomprehensible to me lol. I suck at rust -_-
he used one letter variable names, it’s very incomprehensible.
Get yourself thru the book and you’ll get everything here.
Yeah tried to golf it a bit so its not very readable
Seems like the site doesn’t track characters though so won’t do that for future days
It basically just loops through every character on a line, if it’s a number it sets last to that and if its not a number it checks if theres a substring starting on that point that equals one of the 10 strings that are numbers