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 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 }
Thanks, used this as input for reading the Day 2 file and looping the lines, just getting started with rust :)
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)); } }
My solution in rust. I’m sure there’s a lot more clever ways to do it but this is what I came up with.
Code
use std::{io::prelude::*, fs::File, path::Path, io }; fn main() { run_solution(false); println!("\nPress enter to continue"); let mut buffer = String::new(); io::stdin().read_line(&mut buffer).unwrap(); run_solution(true); } fn run_solution(check_for_spelled: bool) { let data = load_data("data/input"); println!("\nProcessing Data..."); let mut sum: u64 = 0; for line in data.lines() { // Doesn't seem like the to_ascii_lower call is needed but... just in case let first = get_digit(line.to_ascii_lowercase().as_bytes(), false, check_for_spelled); let last = get_digit(line.to_ascii_lowercase().as_bytes(), true, check_for_spelled); let num = (first * 10) + last; // println!("\nLine: {} -- First: {}, Second: {}, Num: {}", line, first, last, num); sum += num as u64; } println!("\nFinal Sum: {}", sum); } fn get_digit(line: &[u8], from_back: bool, check_for_spelled: bool) -> u8 { let mut range: Vec = (0..line.len()).collect(); if from_back { range.reverse(); } for i in range { if is_num(line[i]) { return (line[i] - 48) as u8; } if check_for_spelled { if let Some(num) = is_spelled_num(line, i) { return num; } } } return 0; } fn is_num(c: u8) -> bool { c >= 48 && c <= 57 } fn is_spelled_num(line: &[u8], start: usize) -> Option { let words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; for word_idx in 0..words.len() { let mut i = start; let mut found = true; for c in words[word_idx].as_bytes() { if i < line.len() && *c != line[i] { found = false; break; } i += 1; } if found && i <= line.len() { return Some(word_idx as u8 + 1); } } return None; } fn load_data(file_name: &str) -> String { let mut file = match File::open(Path::new(file_name)) { Ok(file) => file, Err(why) => panic!("Could not open file {}: {}", Path::new(file_name).display(), why), }; let mut s = String::new(); let file_contents = match file.read_to_string(&mut s) { Err(why) => panic!("couldn't read {}: {}", Path::new(file_name).display(), why), Ok(_) => s, }; return file_contents; }
One small thing that would make it easier to read would be to use (I don’t know what the syntax is called) as opposed to the magic numbers for getting the ascii code for a character as a
u8
, e.g.b'0'
instead of48
.Oh yeah that’s a good point. I have seen that before but I didn’t think of it at the time.
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")]))
My solutin in Elixir for both part 1 and part 2 is below. It does use regex and with that there are many different ways to accomplish the goal. I’m no regex master so I made it as simple as possible and relied on the language a bit more. I’m sure there are cooler solutions with no regex too, this is just what I settled on:
https://pastebin.com/u1SYJ4tY
defmodule AdventOfCode.Day01 do def part1(args) do number_regex = ~r/([0-9])/ args |> String.split(~r/\n/, trim: true) |> Enum.map(&first_and_last_number(&1, number_regex)) |> Enum.map(&number_list_to_integer/1) |> Enum.sum() end def part2(args) do number_regex = ~r/(?=(one|two|three|four|five|six|seven|eight|nine|[0-9]))/ args |> String.split(~r/\n/, trim: true) |> Enum.map(&first_and_last_number(&1, number_regex)) |> Enum.map(fn number -> Enum.map(number, &replace_word_with_number/1) end) |> Enum.map(&number_list_to_integer/1) |> Enum.sum() end defp first_and_last_number(string, regex) do matches = Regex.scan(regex, string) [_, first] = List.first(matches) [_, last] = List.last(matches) [first, last] end defp number_list_to_integer(list) do list |> List.to_string() |> String.to_integer() end defp replace_word_with_number(string) do numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] String.replace(string, numbers, fn x -> (Enum.find_index(numbers, &(&1 == x)) + 1) |> Integer.to_string() end) end end
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.
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!
Uiua solution
I may add solutions in Uiua depending on how easy I find them, so here’s today’s (also available to run online):
Inp ← {"four82nine74" "hlpqrdh3" "7qt" "12" "1one"} # if needle is longer than haystack, return zeros SafeFind ← ((⌕|-.;)< ∩⧻ , ,) FindDigits ← (× +1⇡9 ⊠(□SafeFind∩⊔) : Inp) "123456789" ⊜□ ≠@\s . "one two three four five six seven eight nine" ∩FindDigits BuildNum ← (/+∵(/+⊂⊃(×10↙ 1)(↙ 1⇌) ▽≠0.⊔) /↥) ∩BuildNum+,
or stripping away all the fluff:
Inp ← {"four82nine74" "hlpqrdh3" "7qt" "12" "1one"} ⊜□ ≠@\s."one two three four five six seven eight nine" "123456789" ∩(×+1⇡9⊠(□(⌕|-.;)<⊙:∩(⧻.⊔)):Inp) ∩(/+∵(/+⊂⊃(×10↙1)(↙1⇌)▽≠0.⊔)/↥)+,
This is my solution in Nim:
import strutils, strformat const digitStrings = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] ### Type definiton for a proc to extract a calibration function from a line type CalibrationExtracter = proc (line:string): int ## extract a calibration value by finding the first and last numerical digit, and concatenating them proc extractCalibration1(line:string): int = var first,last = -1 for i, c in line: if c.isDigit: last = parseInt($c) if first == -1: first = last result = first * 10 + last ## extract a calibration value by finding the first and last numerical digit OR english lowercase word for a digit, and concatenating them proc extractCalibration2(line:string): int = var first,last = -1 for i, c in line: if c.isDigit: last = parseInt($c) if first == -1: first = last else: #not a digit parse number words for dsi, ds in digitStrings: if i == line.find(ds, i): last = dsi+1 if first == -1: first = last break #break out of digit strings result = first * 10 + last ### general purpose extraction proc, accepts an extraction function for specific line handling proc extract(fileName:string, extracter:CalibrationExtracter, verbose:bool): int = let lines = readFile(fileName).strip().splitLines(); for lineIndex, line in lines: if line.len == 0: continue let value = extracter(line) result += value if verbose: echo &"Extracted {value} from line {lineIndex} {line}" ### public interface for puzzle part 1 proc part1*(input:string, verbose:bool = false): int = result = input.extract(extractCalibration1, verbose); ### public interface for puzzle part 2 proc part2*(input:string, verbose:bool = false): int = result = input.extract(extractCalibration2, verbose);
Oh hey, a fellow nim person. Have you joined the community?
Here’s mine. Kbin doesn’t even support code blocks, so using topaz:
Have you joined the community?
I have now, thanks for the tip!
And that’s some very compact code! I’ve only just started with nim, so seeing more nim solutions is a great way to learn 😁
I’m not doing anything too fancy here, just the first stuff that comes to mind and gets the job done. The filterIt template was pretty handy for part 1, though. I assume at some point in these puzzles I’ll have to actually write some types and procedures instead of just using nested loops for everything.
I think it’s a pretty cool language overall. I’ve only used it for one project so far, so there’s a bunch that I still don’t know. Haven’t been able to wrap my head around how macros work, for example, though I’ve sort of figured out how to write really basic templates.
I looked into the iterators and they are really handy, they remind me of C#'s Linq syntax.
Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn’t work well for people on different instances. Try fixing it like this: !nim@programming.dev
Crystal. Second one was a pain.
part 1
input = File.read("./input.txt").lines sum = 0 input.each do |line| digits = line.chars.select(&.number?) next if digits.empty? num = "#{digits[0]}#{digits[-1]}".to_i sum += num end puts sum
part 2
numbers = { "one"=> "1", "two"=> "2", "three"=> "3", "four"=> "4", "five"=> "5", "six"=> "6", "seven"=> "7", "eight"=> "8", "nine"=> "9", } input.each do |line| start = "" last = "" line.size.times do |i| if line[i].number? start = line[i] break end if i < line.size - 2 && line[i..(i+2)] =~ /one|two|six/ start = numbers[line[i..(i+2)]] break end if i < line.size - 3 && line[i..(i+3)] =~ /four|five|nine/ start = numbers[line[i..(i+3)]] break end if i < line.size - 4 && line[i..(i+4)] =~ /three|seven|eight/ start = numbers[line[i..(i+4)]] break end end (1..line.size).each do |i| if line[-i].number? last = line[-i] break end if i > 2 && line[(-i)..(-i+2)] =~ /one|two|six/ last = numbers[line[(-i)..(-i+2)]] break end if i > 3 && line[(-i)..(-i+3)] =~ /four|five|nine/ last = numbers[line[(-i)..(-i+3)]] break end if i > 4 && line[(-i)..(-i+4)] =~ /three|seven|eight/ last = numbers[line[(-i)..(-i+4)]] break end end sum += "#{start}#{last}".to_i end puts sum
Damn, lemmy’s tabs are massive
Dart solution
This has got to be one of the biggest jumps in trickiness in a Day 1 puzzle. In the end I rolled my part 1 answer into the part 2 logic. [Edit: I’ve golfed it a bit since first posting it]
import 'package:collection/collection.dart'; var ds = '0123456789'.split(''); var wds = 'one two three four five six seven eight nine'.split(' '); int s2d(String s) => s.length == 1 ? int.parse(s) : wds.indexOf(s) + 1; int value(String s, List digits) { var firsts = {for (var e in digits) s.indexOf(e): e}..remove(-1); var lasts = {for (var e in digits) s.lastIndexOf(e): e}..remove(-1); return s2d(firsts[firsts.keys.min]) * 10 + s2d(lasts[lasts.keys.max]); } part1(List lines) => lines.map((e) => value(e, ds)).sum; part2(List lines) => lines.map((e) => value(e, ds + wds)).sum;