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)
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
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.
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().
Solved part one in about thirty seconds. But wow, either my brain is just tired at this hour or I'm lacking in skill, but part two is harder than any other year has been on the first day. Anyway, I managed to solve it, but I absolutely hate it, and will definitely be coming back to try to clean this one up.
impl Solver for Day01 {
fn star_one(&self, input: &str) -> String {
let mut result = 0;
for line in input.lines() {
let line = line
.chars()
.filter(|ch| ch.is_ascii_digit())
.collect::>();
let first = line.first().unwrap();
let last = line.last().unwrap();
let number = format!("{first}{last}").parse::().unwrap();
result += number;
}
result.to_string()
}
fn star_two(&self, input: &str) -> String {
let mut result = 0;
for line in input.lines() {
let mut first = None;
let mut last = None;
while first == None {
for index in 0..line.len() {
let line_slice = &line[index..];
if line_slice.starts_with("one") || line_slice.starts_with("1") {
first = Some(1);
} else if line_slice.starts_with("two") || line_slice.starts_with("2") {
first = Some(2);
} else if line_slice.starts_with("three") || line_slice.starts_with("3") {
first = Some(3);
} else if line_slice.starts_with("four") || line_slice.starts_with("4") {
first = Some(4);
} else if line_slice.starts_with("five") || line_slice.starts_with("5") {
first = Some(5);
} else if line_slice.starts_with("six") || line_slice.starts_with("6") {
first = Some(6);
} else if line_slice.starts_with("seven") || line_slice.starts_with("7") {
first = Some(7);
} else if line_slice.starts_with("eight") || line_slice.starts_with("8") {
first = Some(8);
} else if line_slice.starts_with("nine") || line_slice.starts_with("9") {
first = Some(9);
}
if first.is_some() {
break;
}
}
}
while last == None {
for index in (0..line.len()).rev() {
let line_slice = &line[index..];
if line_slice.starts_with("one") || line_slice.starts_with("1") {
last = Some(1);
} else if line_slice.starts_with("two") || line_slice.starts_with("2") {
last = Some(2);
} else if line_slice.starts_with("three") || line_slice.starts_with("3") {
last = Some(3);
} else if line_slice.starts_with("four") || line_slice.starts_with("4") {
last = Some(4);
} else if line_slice.starts_with("five") || line_slice.starts_with("5") {
last = Some(5);
} else if line_slice.starts_with("six") || line_slice.starts_with("6") {
last = Some(6);
} else if line_slice.starts_with("seven") || line_slice.starts_with("7") {
last = Some(7);
} else if line_slice.starts_with("eight") || line_slice.starts_with("8") {
last = Some(8);
} else if line_slice.starts_with("nine") || line_slice.starts_with("9") {
last = Some(9);
}
if last.is_some() {
break;
}
}
}
result += format!("{}{}", first.unwrap(), last.unwrap())
.parse::()
.unwrap();
}
result.to_string()
}
}
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;
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)
// 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);
};
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 -_-
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.โ)/โฅ)+,
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
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;
}
execute(1, test_file_suffix: "p1") do |lines|
lines.inject(0) do |acc, line|
d = line.gsub(/\D/,'')
acc += (d[0] + d[-1]).to_i
end
end
Part 2
map = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
execute(2) do |lines|
lines.inject(0) do |acc, line|
first_num = line.sub(/(one|two|three|four|five|six|seven|eight|nine)/) do |key|
map[key.to_sym]
end
last_num = line.reverse.sub(/(enin|thgie|neves|xis|evif|ruof|eerht|owt|eno)/) do |key|
map[key.reverse.to_sym]
end
d = first_num.chars.select { |num| numeric?(num) }
e = last_num.chars.select { |num| numeric?(num) }
acc += (d[0] + e[0]).to_i
end
end
Then of course I also code golfed it, but didn't try very hard.
P1 Code Golf
execute(1, alternative_text: "Code Golf 60 bytes", test_file_suffix: "p1") do |lines|
lines.inject(0){|a,l|d=l.gsub(/\D/,'');a+=(d[0]+d[-1]).to_i}
end
P2 Code Golf (ignore the formatting, I just didn't want to reformat to remove all the spaces, and it's easier to read this way.)
execute(1, alternative_text: "Code Golf 271 bytes", test_file_suffix: "p1") do |z|
z.inject(0) { |a, l|
w = %w(one two three four five six seven eight nine)
x = w.join(?|)
f = l.sub(/(#{x})/) { |k| map[k.to_sym] }
g = l.reverse.sub(/(#{x.reverse})/) { |k| map[k.reverse.to_sym] }
d = f.chars.select { |n| n.match?(/\d/) }
e = g.chars.select { |n| n.match?(/\d/) }
a += (d[0] + e[0]).to_i
}
end
Thank you for sharing this. I also wrote a regular expression with \d|eno|owt and so on, and I was not so proud of myself :). Good to know I wasn't the only one :).
I was trying so hard to avoid doing this and landed on a pretty nice solution (for me). It's funny sering everyone's approach especially when you have no problem running through that barrier that I didn't want to ๐
haha it's such a dumb solution, but it works. i've seen several others that have done the same thing. The alternatives all sounded too hard for my tired brain.
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 so one3m becomes ["","o","on","one","one3","one3m","","n","ne","ne3","ne3m","","e","e3","e3m","","3","3m","","m",""]. I then wrote a function stringToDigit :: String -> Maybe Char which simultaneously filtered out the digits and standardised them as Chars.
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!
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);
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: [email protected]
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
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
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)
I'm trying to practice writing clear, commented, testable functions, so I added some things that are strictly unnecessary for the challenge (docstrings, error raising, type hints, tests...), but I think it's a necessary exercise for me. If anyone has comments or criticism about my attempt at "best practices," please let me know!
Also, I thought it was odd that the correct answer to part 2 requires that you allow for overlapping letters such as "threeight", but that doesn't occur in the sample input. I imagine that many people will hit a wall wondering why their answer is rejected.
day01.py
import re
from pathlib import Path
DIGITS = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
r"\d",
]
PATTERN_PART_1 = r"\d"
PATTERN_PART_2 = f"(?=({'|'.join(DIGITS)}))"
def get_digit(s: str) -> int:
"""Return the digit in the input
Args:
s (str): one string containing a single digit represented by a single arabic numeral or spelled out in lower-case English
Returns:
int: the digit as an integer value
"""
try:
return int(s)
except ValueError:
return DIGITS.index(s)
def calibration_value(line: str, pattern: str) -> int:
"""Return the calibration value in the input
Args:
line (str): one line containing a calibration value
pattern (str): the regular expression pattern to match
Raises:
ValueError: if no digits are found in the line
Returns:
int: the calibration value
"""
digits = re.findall(pattern, line)
if digits:
return get_digit(digits[0]) * 10 + get_digit(digits[-1])
raise ValueError(f"No digits found in: '{line}'")
def calibration_sum(lines: str, pattern: str) -> int:
"""Return the sum of the calibration values in the input
Args:
lines (str): one or more lines containing calibration values
Returns:
int: the sum of the calibration values
"""
sum = 0
for line in lines.split("\n"):
sum += calibration_value(line, pattern)
return sum
if __name__ == "__main__":
path = Path(__file__).resolve().parent / "input" / "day01.txt"
lines = path.read_text().strip()
print("Sum of calibration values:")
print(f"โข Part 1: {calibration_sum(lines, PATTERN_PART_1)}")
print(f"โข Part 2: {calibration_sum(lines, PATTERN_PART_2)}")
test_day01.py
import pytest
from advent_2023_python.day01 import (
calibration_value,
calibration_sum,
PATTERN_PART_1,
PATTERN_PART_2,
)
LINES_PART_1 = [
("1abc2", 12),
("pqr3stu8vwx", 38),
("a1b2c3d4e5f", 15),
("treb7uchet", 77),
]
BLOCK_PART_1 = (
"\n".join([line[0] for line in LINES_PART_1]),
sum(line[1] for line in LINES_PART_1),
)
LINES_PART_2 = [
("two1nine", 29),
("eightwothree", 83),
("abcone2threexyz", 13),
("xtwone3four", 24),
("4nineeightseven2", 42),
("zoneight234", 14),
("7pqrstsixteen", 76),
]
BLOCK_PART_2 = (
"\n".join([line[0] for line in LINES_PART_2]),
sum(line[1] for line in LINES_PART_2),
)
def test_part_1():
for line in LINES_PART_1:
assert calibration_value(line[0], PATTERN_PART_1) == line[1]
assert calibration_sum(BLOCK_PART_1[0], PATTERN_PART_1) == BLOCK_PART_1[1]
def test_part_2_with_part_1_values():
for line in LINES_PART_1:
assert calibration_value(line[0], PATTERN_PART_2) == line[1]
assert calibration_sum(BLOCK_PART_1[0], PATTERN_PART_2) == BLOCK_PART_1[1]
def test_part_2_with_part_2_values():
for line in LINES_PART_2:
assert calibration_value(line[0], PATTERN_PART_2) == line[1]
assert calibration_sum(BLOCK_PART_2[0], PATTERN_PART_2) == BLOCK_PART_2[1]
def test_no_digits():
with pytest.raises(ValueError):
calibration_value("abc", PATTERN_PART_1)
with pytest.raises(ValueError):
calibration_value("abc", PATTERN_PART_2)
I did this in C. First part was fairly trivial, iterate over the line, find first and last number, easy.
Second part had me a bit worried i would need a more string friendly library/language, until i worked out that i can just strstr to find "one", and then in place switch that to "o1e", and so on. Then run part1 code over the modified buffer. I originally did "1ne", but overlaps such as "eightwo" meant that i got the 2, but missed the 8.
#include
#include
#include
#include
#include
size_t readfile(char* fname, char* buffer, size_t buffer_len)
{
int f = open(fname, 'r');
assert(f >= 0);
size_t total = 0;
do {
size_t nr = read(f, buffer + total, buffer_len - total);
if (nr == 0) {
return total;
}
total += nr;
}
while (buffer_len - total > 0);
return -1;
}
int part1(const char* buffer, size_t buffer_len)
{
int first = -1;
int last = -1;
int total = 0;
for (int i = 0; i < buffer_len; i++)
{
char c = buffer[i];
if (c == '\n')
{
if (first == -1) {
continue;
}
total += (first*10 + last);
first = last = -1;
continue;
}
int val = c - '0';
if (val > 9 || val < 0)
{
continue;
}
if (first == -1)
{
first = last = val;
}
else
{
last = val;
}
}
return total;
}
void part2_sanitize(char* buffer, size_t len)
{
char* p = NULL;
while ((p = strnstr(buffer, "one", len)) != NULL)
{
p[1] = '1';
}
while ((p = strnstr(buffer, "two", len)) != NULL)
{
p[1] = '2';
}
while ((p = strnstr(buffer, "three", len)) != NULL)
{
p[1] = '3';
}
while ((p = strnstr(buffer, "four", len)) != NULL)
{
p[1] = '4';
}
while ((p = strnstr(buffer, "five", len)) != NULL)
{
p[1] = '5';
}
while ((p = strnstr(buffer, "six", len)) != NULL)
{
p[1] = '6';
}
while ((p = strnstr(buffer, "seven", len)) != NULL)
{
p[1] = '7';
}
while ((p = strnstr(buffer, "eight", len)) != NULL)
{
p[1] = '8';
}
while ((p = strnstr(buffer, "nine", len)) != NULL)
{
p[1] = '9';
}
while ((p = strnstr(buffer, "zero", len)) != NULL)
{
p[1] = '0';
}
}
int main(int argc, char** argv)
{
assert(argc == 2);
char buffer[1000000];
size_t len = readfile(argv[1], buffer, sizeof(buffer));
{
int total = part1(buffer, len);
printf("Part 1 total: %i\n", total);
}
{
part2_sanitize(buffer, len);
int total = part1(buffer, len);
printf("Part 2 total: %i\n", total);
}
}
Just realised how inefficient the sanitize function is, it iterates over the buffer way too many times. Should be restarting the strnstr from the location of the last hit instead of from the start.
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();
}
Did this in Odin (very hashed together, especially finding the last number in part 2):
spoiler
package day1
import "core:fmt"
import "core:strings"
import "core:strconv"
import "core:unicode"
p1 :: proc(input: []string) {
total := 0
for line in input {
firstNum := line[strings.index_proc(line, unicode.is_digit):][:1]
lastNum := line[strings.last_index_proc(line, unicode.is_digit):][:1]
calibrationValue := strings.concatenate({firstNum, lastNum})
defer delete(calibrationValue)
num, ok := strconv.parse_int(calibrationValue)
total += num
}
// daggonit thought it was the whole numbers
/*
for line in input {
firstNum := line
fFrom := strings.index_proc(firstNum, unicode.is_digit)
firstNum = firstNum[fFrom:]
fTo := strings.index_proc(firstNum, proc(r:rune)->bool {return !unicode.is_digit(r)})
if fTo == -1 do fTo = len(firstNum)
firstNum = firstNum[:fTo]
lastNum := line
lastNum = lastNum[:strings.last_index_proc(lastNum, unicode.is_digit)+1]
lastNum = lastNum[strings.last_index_proc(lastNum, proc(r:rune)->bool {return !unicode.is_digit(r)})+1:]
calibrationValue := strings.concatenate({firstNum, lastNum})
defer delete(calibrationValue)
num, ok := strconv.parse_int(calibrationValue, 10)
if !ok {
fmt.eprintf("%s could not be parsed from %s", calibrationValue, line)
return
}
total += num;
}
*/
fmt.println(total)
}
p2 :: proc(input: []string) {
parse_wordable :: proc(s: string) -> int {
if len(s) == 1 {
num, ok := strconv.parse_int(s)
return num
} else do switch s {
case "one" : return 1
case "two" : return 2
case "three": return 3
case "four" : return 4
case "five" : return 5
case "six" : return 6
case "seven": return 7
case "eight": return 8
case "nine" : return 9
}
return -1
}
total := 0
for line in input {
firstNumI, firstNumW := strings.index_multi(line, {
"one" , "1",
"two" , "2",
"three", "3",
"four" , "4",
"five" , "5",
"six" , "6",
"seven", "7",
"eight", "8",
"nine" , "9",
})
firstNum := line[firstNumI:][:firstNumW]
// last_index_multi doesn't seem to exist, doing this as backup
lastNumI, lastNumW := -1, -1
for {
nLastNumI, nLastNumW := strings.index_multi(line[lastNumI+1:], {
"one" , "1",
"two" , "2",
"three", "3",
"four" , "4",
"five" , "5",
"six" , "6",
"seven", "7",
"eight", "8",
"nine" , "9",
})
if nLastNumI == -1 do break
lastNumI += nLastNumI+1
lastNumW = nLastNumW
}
lastNum := line[lastNumI:][:lastNumW]
total += parse_wordable(firstNum)*10 + parse_wordable(lastNum)
}
fmt.println(total)
}
Had a ton of trouble with part 1 until I realized I misinterpreted it. Especially annoying because the example was working fine. So paradoxically part 2 was easier than 1.
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 I filter
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.
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)