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
Just getting my feet wet with coding after a decade of 0 programming. CS just didn’t work out for me in school, so I swapped over to math. Trying to use Python on my desktop, with Notepad++ and Windows Shell.
Part 1
with open('01A_input.txt', 'r') as file: data = file.readlines() print(data) NumericList=[] for row in data: word=row while not(word[0].isnumeric()): word=word[1:] while not(word[-1].isnumeric()): word=word[:-1] #print(word) tempWord=word[0]+word[-1] NumericList.append(int(tempWord)) #print(NumericList) Total=sum(NumericList) print(Total)
Part 2
with open('01A_input.txt', 'r') as file: data = file.readlines() #print(data) NumericList=[] NumberWords=("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") def wordreplaceleft(wrd): if wrd.startswith("one"): return "1" + wrd[3:] elif wrd.startswith("two"): return "2" + wrd[3:] elif wrd.startswith("three"): return "3" + wrd[5:] elif wrd.startswith("four"): return "4" + wrd[4:] elif wrd.startswith("five"): return "5" + wrd[4:] elif wrd.startswith("six"): return "6" + wrd[3:] elif wrd.startswith("seven"): return "7" + wrd[5:] elif wrd.startswith("eight"): return "8" + wrd[5:] elif wrd.startswith("nine"): return "9" + wrd[4:] def wordreplaceright(wrd): if wrd.endswith("one"): return wrd[:-3]+"1" elif wrd.endswith("two"): return wrd[:-3]+"2" elif wrd.endswith("three"): return wrd[:-5]+"3" elif wrd.endswith("four"): return wrd[:-4]+"4" elif wrd.endswith("five"): return wrd[:-4]+"5" elif wrd.endswith("six"): return wrd[:-3]+"6" elif wrd.endswith("seven"): return wrd[:-5]+"7" elif wrd.endswith("eight"): return wrd[:-5]+"8" elif wrd.endswith("nine"): return wrd[:-4]+"9" for row in data: wordleft=row wordright=row if wordleft.startswith(NumberWords): wordleft=wordreplaceleft(wordleft) while not(wordleft[0].isnumeric()): if wordleft.startswith(NumberWords): wordleft=wordreplaceleft(wordleft) else: wordleft=wordleft[1:] if wordright.endswith(NumberWords): wordright=wordreplaceright(wordright) while not(wordright[-1].isnumeric()): if wordright.endswith(NumberWords): wordright=wordreplaceright(wordright) else: wordright=wordright[:-1] # while not(word[-1].isnumeric()): # word=word[:-1] # print(word) tempWord=wordleft[0]+wordright[-1] NumericList.append(int(tempWord)) #print(NumericList) Total=sum(NumericList) print(Total)
I know my entire thing is kinda super hobbled together. Any recommendations on how I can make this all easier on myself?
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 }
Thanks, used this as input for reading the Day 2 file and looping the lines, just getting started with rust :)
Have a snippet of Ruby, something I hacked together as part of a solution during the WFH morning meeting;
class String def to_numberstring(digits_only: false) tokens = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }.freeze ret = "" i = 0 loop do if self[i] =~ /\d/ ret += self[i] elsif !digits_only tok = tokens.find { |k, _| self[i, k.size] == k.to_s } ret += tok.last.to_s if tok end i += 1 break if i >= size end ret end end
Part-A in Python: https://github.com/pbui/advent-of-code-2023/blob/master/day01/day01-A.py
Was able to use a list comprehension to read the input.
Part-B in Python: https://github.com/pbui/advent-of-code-2023/blob/master/day01/day01-B.py
This was trickier…
Hint
You have to account for overlapping words such as:
eightwo
. This actually simplifies things as you just need to go letter by letter and check if it is a digit or one of the words.Update: Modified Part 2 to be more functional again by using a
map
before Ifilter
Re. your hint, that’s funny because I skipped the obvious optimization of skipping over matched letters out of laziness, but it would’ve actually broken the solution.
Trickier than expected! I ran into an issue with Lua patterns, so I had to revert to a more verbose solution, which I then used in Hare as well.
Lua:
lua
-- SPDX-FileCopyrightText: 2023 Jummit -- -- SPDX-License-Identifier: GPL-3.0-or-later local sum = 0 for line in io.open("1.input"):lines() do local a, b = line:match("^.-(%d).*(%d).-$") if not a then a = line:match("%d+") b = a end if a and b then sum = sum + tonumber(a..b) end end print(sum) local names = { ["one"] = 1, ["two"] = 2, ["three"] = 3, ["four"] = 4, ["five"] = 5, ["six"] = 6, ["seven"] = 7, ["eight"] = 8, ["nine"] = 9, ["1"] = 1, ["2"] = 2, ["3"] = 3, ["4"] = 4, ["5"] = 5, ["6"] = 6, ["7"] = 7, ["8"] = 8, ["9"] = 9, } sum = 0 for line in io.open("1.input"):lines() do local firstPos = math.huge local first for name, num in pairs(names) do local left = line:find(name) if left and left < firstPos then firstPos = left first = num end end local last for i = #line, 1, -1 do for name, num in pairs(names) do local right = line:find(name, i) if right then last = num goto found end end end ::found:: sum = sum + tonumber(first * 10 + last) end print(sum)
Hare:
hare
// SPDX-FileCopyrightText: 2023 Jummit // // SPDX-License-Identifier: GPL-3.0-or-later use fmt; use types; use bufio; use strings; use io; use os; const numbers: [](str, int) = [ ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5), ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9), ("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5), ("6", 6), ("7", 7), ("8", 8), ("9", 9), ]; fn solve(start: size) void = { const file = os::open("1.input")!; defer io::close(file)!; const scan = bufio::newscanner(file, types::SIZE_MAX); let sum = 0; for (let i = 1u; true; i += 1) { const line = match (bufio::scan_line(&scan)!) { case io::EOF => break; case let line: const str => yield line; }; let first: (void | int) = void; let last: (void | int) = void; for (let i = 0z; i < len(line); i += 1) :found { for (let num = start; num < len(numbers); num += 1) { const start = strings::sub(line, i, strings::end); if (first is void && strings::hasprefix(start, numbers[num].0)) { first = numbers[num].1; }; const end = strings::sub(line, len(line) - 1 - i, strings::end); if (last is void && strings::hasprefix(end, numbers[num].0)) { last = numbers[num].1; }; if (first is int && last is int) { break :found; }; }; }; sum += first as int * 10 + last as int; }; fmt::printfln("{}", sum)!; }; export fn main() void = { solve(9); solve(0); };
deleted by creator
deleted by creator
Note you can put this on a separate post and should get some responses from that
(this is supposed to be for solutions only so people arent browsing it to solve help requests)
Oh sorry, just saw this thread and got excited, will delete to keep it clean
The problem is probably that letters can overlap:
eightwo -> 82 instead of 88
[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); }
Started a bit late due to setting up the thread and monitoring the leaderboard to open it up but still got it decently quick for having barely touched rust
Probably able to get it down shorter so might revisit it
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 -_-
In case that this might help.
h.chars() returns an iterator of characters. Then he concatenate chars and see if it’s a digit or a number string.
You can swap match u.is_numeric() with if u.is_numeric and covert _ => branch to else.
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
Oh, doing this is Rust is really simple.
I tried doing the same thing in Rust, but ended up doing it in Python instead.
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
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);
Solution in C: https://github.com/sjmulder/aoc/blob/master/2023/c/day01-orig.c
Usually day 1 solutions are super short numeric things, this was a little more verbose. For part 2 I just loop over an array of digit names and use
strncmp()
.int main(int argc, char **argv) { static const char * const nm[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; char buf[64], *s; int p1=0,p2=0, p1f,p1l, p2f,p2l, d; while (fgets(buf, sizeof(buf), stdin)) { p1f = p1l = p2f = p2l = -1; for (s=buf; *s; s++) if (*s >= '0' && *s <= '9') { d = *s-'0'; if (p1f == -1) p1f = d; if (p2f == -1) p2f = d; p1l = p2l = d; } else for (d=0; d<10; d++) { if (strncmp(s, nm[d], strlen(nm[d]))) continue; if (p2f == -1) p2f = d; p2l = d; break; } p1 += p1f*10 + p1l; p2 += p2f*10 + p2l; } printf("%d %d\n", p1, p2); return 0; }
Part 1 felt fairly pretty simple in Haskell:
import Data.Char (isDigit) main = interact solve solve :: String -> String solve = show . sum . map (read . (\x -> [head x, last x]) . filter isDigit) . lines
Part 2 was more of a struggle, though I’m pretty happy with how it turned out. I ended up using
concatMap inits . tails
to generate all substrings, in order of appearance soone3m
becomes["","o","on","one","one3","one3m","","n","ne","ne3","ne3m","","e","e3","e3m","","3","3m","","m",""]
. I then wrote a functionstringToDigit :: String -> Maybe Char
which simultaneously filtered out the digits and standardised them asChar
s.import Data.List (inits, tails) import Data.Char (isDigit, digitToInt) import Data.Maybe (mapMaybe) main = interact solve solve :: String -> String solve = show . sum . map (read . (\x -> [head x, last x]) . mapMaybe stringToDigit . concatMap inits . tails) . lines -- |string of first&last digit| |find all the digits | |all substrings of line| stringToDigit "one" = Just '1' stringToDigit "two" = Just '2' stringToDigit "three" = Just '3' stringToDigit "four" = Just '4' stringToDigit "five" = Just '5' stringToDigit "six" = Just '6' stringToDigit "seven" = Just '7' stringToDigit "eight" = Just '8' stringToDigit "nine" = Just '9' stringToDigit [x] | isDigit x = Just x | otherwise = Nothing stringToDigit _ = Nothing
I went a bit excessively Haskell with it, but I had my fun!
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.
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)