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


πŸ”’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

8 points

Python 3

I had some trouble getting Part 2 to work, until I realized that there could be overlap ( blbleightwoqsqs -> 82).

spoiler
import re

def puzzle_one():
    result_sum = 0
    with open("inputs/day_01", "r", encoding="utf_8") as input_file:
        for line in input_file:
            number_list = [char for char in line if char.isnumeric()]
            number = int(number_list[0] + number_list[-1])
            result_sum += number
    return result_sum

def puzzle_two():
    regex = r"(?=(zero|one|two|three|four|five|six|seven|eight|nine|[0-9]))"
    number_dict = {
        "zero": "0",
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6",
        "seven": "7",
        "eight": "8",
        "nine": "9",
    }
    result_sum = 0
    with open("inputs/day_01", "r", encoding="utf_8") as input_file:
        for line in input_file:
            number_list = [
                number_dict[num] if num in number_dict else num
                for num in re.findall(regex, line)
            ]
            number = int(number_list[0] + number_list[-1])
            result_sum += number
    return result_sum

I still have a hard time understanding regex, but I think it’s getting there.

permalink
report
reply
8 points
*

Rust

Part 1 Part 2

Fun with iterators! For the second part I went to regex for help.

permalink
report
reply
6 points
*

A new C solution: without lookahead or backtracking! I keep a running tally of how many letters of each digit word were matched so far: https://github.com/sjmulder/aoc/blob/master/2023/c/day01.c

int main(int argc, char **argv)
{
	static const char names[][8] = {"zero", "one", "two", "three",
	    "four", "five", "six", "seven", "eight", "nine"};
	int p1=0, p2=0, i,c;
	int p1_first = -1, p1_last = -1;
	int p2_first = -1, p2_last = -1;
	int nmatched[10] = {0};
	
	while ((c = getchar()) != EOF)
		if (c == '\n') {
			p1 += p1_first*10 + p1_last;
			p2 += p2_first*10 + p2_last;
			p1_first = p1_last = p2_first = p2_last = -1;
			memset(nmatched, 0, sizeof(nmatched));
		} else if (c >= '0' && c <= '9') {
			if (p1_first == -1) p1_first = c-'0';
			if (p2_first == -1) p2_first = c-'0';
			p1_last = p2_last = c-'0';
			memset(nmatched, 0, sizeof(nmatched));
		} else for (i=0; i<10; i++)
			/* advance or reset no. matched digit chars */
			if (c != names[i][nmatched[i]++])
				nmatched[i] = c == names[i][0];
			/* matched to end? */
			else if (!names[i][nmatched[i]]) {
				if (p2_first == -1) p2_first = i;
				p2_last = i;
				nmatched[i] = 0;
			}

	printf("%d %d\n", p1, p2);
	return 0;
}
permalink
report
reply
3 points

And golfed down:

char*N[]={0,"one","two","three","four","five","six","seven","eight","nine"};p,P,
i,c,a,b;A,B;m[10];main(){while((c=getchar())>0){c==10?p+=a*10+b,P+=A*10+B,a=b=A=
B=0:0;c>47&&c<58?b=B=c-48,a||(a=b),A||(A=b):0;for(i=10;--i;)c!=N[i][m[i]++]?m[i]
=c==*N[i]:!N[i][m[i]]?A||(A=i),B=i:0;}printf("%d %d\n",p,P);
permalink
report
parent
reply
5 points
*

I finally got my solutions done. I used rust. I feel like 114 lines (not including empty lines or driver code) for both solutions is pretty decent. If lemmy’s code blocks are hard to read, I also put my solutions on github.

use std::{
    cell::OnceCell,
    collections::{HashMap, VecDeque},
    ops::ControlFlow::{Break, Continue},
};

use crate::utils::read_lines;

#[derive(Clone, Copy, PartialEq, Eq)]
enum NumType {
    Digit,
    DigitOrWord,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum FromDirection {
    Left,
    Right,
}

const WORD_NUM_MAP: OnceCell> = OnceCell::new();

fn init_num_map() -> HashMap<&'static str, u8> {
    HashMap::from([
        ("one", b'1'),
        ("two", b'2'),
        ("three", b'3'),
        ("four", b'4'),
        ("five", b'5'),
        ("six", b'6'),
        ("seven", b'7'),
        ("eight", b'8'),
        ("nine", b'9'),
    ])
}

const MAX_WORD_LEN: usize = 5;

fn get_digit<i>(mut bytes: I, num_type: NumType, from_direction: FromDirection) -> Option
where
    I: Iterator,
{
    let digit = bytes.try_fold(VecDeque::new(), |mut byte_queue, byte| {
        if byte.is_ascii_digit() {
            Break(byte)
        } else if num_type == NumType::DigitOrWord {
            if from_direction == FromDirection::Left {
                byte_queue.push_back(byte);
            } else {
                byte_queue.push_front(byte);
            }

            let word = byte_queue
                .iter()
                .map(|&amp;byte| byte as char)
                .collect::();

            for &amp;key in WORD_NUM_MAP
                .get_or_init(init_num_map)
                .keys()
                .filter(|k| k.len() &lt;= byte_queue.len())
            {
                if word.contains(key) {
                    return Break(*WORD_NUM_MAP.get_or_init(init_num_map).get(key).unwrap());
                }
            }

            if byte_queue.len() == MAX_WORD_LEN {
                if from_direction == FromDirection::Left {
                    byte_queue.pop_front();
                } else {
                    byte_queue.pop_back();
                }
            }

            Continue(byte_queue)
        } else {
            Continue(byte_queue)
        }
    });

    if let Break(byte) = digit {
        Some(byte)
    } else {
        None
    }
}

fn process_digits(x: u8, y: u8) -> u16 {
    ((10 * (x - b'0')) + (y - b'0')).into()
}

fn solution(num_type: NumType) {
    if let Ok(lines) = read_lines("src/day_1/input.txt") {
        let sum = lines.fold(0_u16, |acc, line| {
            let line = line.unwrap_or_else(|_| String::new());
            let bytes = line.bytes();
            let left = get_digit(bytes.clone(), num_type, FromDirection::Left).unwrap_or(b'0');
            let right = get_digit(bytes.rev(), num_type, FromDirection::Right).unwrap_or(left);

            acc + process_digits(left, right)
        });

        println!("{sum}");
    }
}

pub fn solution_1() {
    solution(NumType::Digit);
}

pub fn solution_2() {
    solution(NumType::DigitOrWord);
}
```</i>
permalink
report
reply
5 points
*
import re
numbers = {
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4,
    "five" : 5,
    "six" : 6,
    "seven" : 7,
    "eight" : 8,
    "nine" : 9
    }
for digit in range(10):
    numbers[str(digit)] = digit
pattern = "(%s)" % "|".join(numbers.keys())
   
re1 = re.compile(".*?" + pattern)
re2 = re.compile(".*" + pattern)
total = 0
for line in open("input.txt"):
    m1 = re1.match(line)
    m2 = re2.match(line)
    num = (numbers[m1.group(1)] * 10) + numbers[m2.group(1)]
    total += num
print(total)

There weren’t any zeros in the training data I got - the text seems to suggest that β€œ0” is allowed but β€œzero” isn’t.

permalink
report
reply
2 points

That’s very close to how I solved part 2 as well. Using the greedy wildcard in the regex to find the last number is quite elegant.

permalink
report
parent
reply
1 point
Deleted by creator
permalink
report
parent
reply

Advent Of Code

!advent_of_code@programming.dev

Create post

An unofficial home for the advent of code community on programming.dev!

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.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

  • Follow the programming.dev instance rules
  • Keep all content related to advent of code in some way
  • If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2023 Day 10])
  • When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

Community stats

  • 1

    Monthly active users

  • 75

    Posts

  • 858

    Comments