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
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.
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;
}
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);
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(|&byte| byte as char)
.collect::();
for &key in WORD_NUM_MAP
.get_or_init(init_num_map)
.keys()
.filter(|k| k.len() <= 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>
Part 02 in Rust π¦ :
use std::{
collections::HashMap,
env, fs,
io::{self, BufRead, BufReader},
};
fn main() -> io::Result<()> {
let args: Vec = env::args().collect();
let filename = &args[1];
let file = fs::File::open(filename)?;
let reader = BufReader::new(file);
let number_map = HashMap::from([
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9"),
]);
let mut total = 0;
for _line in reader.lines() {
let digits = get_text_numbers(_line.unwrap(), &number_map);
if !digits.is_empty() {
let digit_first = digits.first().unwrap();
let digit_last = digits.last().unwrap();
let mut cat = String::new();
cat.push(*digit_first);
cat.push(*digit_last);
let cat: i32 = cat.parse().unwrap();
total += cat;
}
}
println!("{total}");
Ok(())
}
fn get_text_numbers(text: String, number_map: &HashMap<&str, &str>) -> Vec {
let mut digits: Vec = Vec::new();
if text.is_empty() {
return digits;
}
let mut sample = String::new();
let chars: Vec = text.chars().collect();
let mut ptr1: usize = 0;
let mut ptr2: usize;
while ptr1 < chars.len() {
sample.clear();
ptr2 = ptr1 + 1;
if chars[ptr1].is_digit(10) {
digits.push(chars[ptr1]);
sample.clear();
ptr1 += 1;
continue;
}
sample.push(chars[ptr1]);
while ptr2 < chars.len() {
if chars[ptr2].is_digit(10) {
sample.clear();
break;
}
sample.push(chars[ptr2]);
if number_map.contains_key(&sample.as_str()) {
let str_digit: char = number_map.get(&sample.as_str()).unwrap().parse().unwrap();
digits.push(str_digit);
sample.clear();
break;
}
ptr2 += 1;
}
ptr1 += 1;
}
digits
}