Day 6: Wait for It
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/ , pastebin, or github (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
Nim
Hey, waitaminute, this isn’t a programming puzzle. This is algebra homework!
Part 2 only required a trivial change to the parsing, the rest of the code still worked. I kept the data as singleton arrays to keep it compatible.
Rust
Feedback welcome! Feel like I’m getting the hand of Rust more and more.
use regex::Regex; pub fn part_1(input: &str) { let lines: Vec<&str> = input.lines().collect(); let time_data = number_string_to_vec(lines[0]); let distance_data = number_string_to_vec(lines[1]); // Zip time and distance into a single iterator let data_iterator = time_data.iter().zip(distance_data.iter()); let mut total_possible_wins = 1; for (time, dist_req) in data_iterator { total_possible_wins *= calc_possible_wins(*time, *dist_req) } println!("part possible wins: {:?}", total_possible_wins); } pub fn part_2(input: &str) { let lines: Vec<&str> = input.lines().collect(); let time_data = number_string_to_vec(&lines[0].replace(" ", "")); let distance_data = number_string_to_vec(&lines[1].replace(" ", "")); let total_possible_wins = calc_possible_wins(time_data[0], distance_data[0]); println!("part 2 possible wins: {:?}", total_possible_wins); } pub fn calc_possible_wins(time: u64, dist_req: u64) -> u64 { let mut ways_to_win: u64 = 0; // Second half is a mirror of the first half, so only calculate first part for push_time in 1..=time / 2 { // If a push_time crosses threshold the following ones will too so break loop if push_time * (time - push_time) > dist_req { // There are (time+1) options (including 0). // Subtract twice the minimum required push time, also removing the longest push times ways_to_win += time + 1 - 2 * push_time; break; } } ways_to_win } fn number_string_to_vec(input: &str) -> Vec { let regex_number = Regex::new(r"\d+").unwrap(); let numbers: Vec = regex_number .find_iter(input) .filter_map(|m| m.as_str().parse().ok()) .collect(); numbers }
I’m no rust expert, but:
you can use
into_iter()
instead ofiter()
to get owned data (if you’re not going to use the original container again). Withinto_iter()
you dont have to deref the values every time which is nice.Also it’s small potatoes, but calling
input.lines().collect()
allocates a vector (that isnt ever used again) whenlines()
returns an iterator that you can use directly. You can instead passlines.next().unwrap()
into your functions directly.Strings have a method called
split_whitespace()
(also asplit_ascii_whitespace()
) that returns an iterator over tokens separated by any amount of whitespace. You can then call.collect()
with a String turbofish (i’d type it out but lemmy’s markdown is killing me) on that iterator. Iirc that ends up being faster because replacing characters with an empty character requires you to shift all the following characters backward each time.Overall really clean code though. One of my favorite parts of using rust (and pain points of going back to other languages) is the crazy amount of helper functions for common operations on basic types.
Edit: oh yeah, also strings have a
.parse()
method to converts it to a number e.g.data.parse()
where the parse takes a turbo fish of the numeric type. As always, turbofishes arent required if rust already knows the type of the variable it’s being assigned to.Thanks for making some time to check my code, really appreciated! the split_whitespace is super useful, for some reason I expected it to just split on single spaces, so I was messing with trim() stuff the whole time :D. Could immediately apply this feedback to the Challenge of today! I’ve now created a general function I can use for these situations every time:
input.split_whitespace() .map(|m| m.parse().expect("can't parse string to int")) .collect() }
Thanks again!
Well, this one ended up being a really nice and terse solution when done naïvely, here with a trimmed snippet from my simple solution;
Ruby
puts "Part 1:", @races.map do |race| (0..race[:time]).count { |press_dur| press_dur * (race[:time] - press_dur) > race[:distance] } end.inject(:*) full_race_time = @races.map { |r| r[:time].to_s }.join.to_i full_race_dist = @races.map { |r| r[:distance].to_s }.join.to_i puts "Part 2:", (0..full_race_time).count { |press_dur| press_dur * (full_race_time - press_dur) > full_race_dist }
Rust:
For part 2, all I did was edit the input and change
i32
toi64
.spoiler
use std::fs; use std::path::PathBuf; use clap::Parser; #[derive(Parser)] #[command(author, version, about, long_about = None)] struct Cli { input_file: PathBuf, } fn main() { // Parse CLI arguments let cli = Cli::parse(); // Read file let input_text = fs::read_to_string(&cli.input_file) .expect(format!("File \"{}\" not found", cli.input_file.display()).as_str()); let input_lines: Vec<&str> = input_text.lines().collect(); let times: Vec = input_lines[0] .split_ascii_whitespace() .skip(1) .map(|s| s.parse().unwrap()) .collect(); let distances: Vec = input_lines[1] .split_ascii_whitespace() .skip(1) .map(|s| s.parse().unwrap()) .collect(); println!("{:?}", times); println!("{:?}", distances); let mut product: i64 = 1; for (time, distance) in times.iter().zip(distances) { let mut n = 0; for b in 0..*time { if time * b - b * b > distance { n += 1; } } product *= n; } println!("{}", product) }
Haskell
This problem has a nice closed form solution, but brute force also works.
(My keyboard broke during part two. Yet another day off the bottom of the leaderboard…)
import Control.Monad import Data.Bifunctor import Data.List readInput :: String -> [(Int, Int)] readInput = map (\[t, d] -> (read t, read d)) . tail . transpose . map words . lines -- Quadratic formula wins :: (Int, Int) -> Int wins (t, d) = let c = fromIntegral t / 2 :: Double h = sqrt (fromIntegral $ t * t - 4 * d) / 2 in ceiling (c + h) - floor (c - h) - 1 main = do input <- readInput <$> readFile "input06" print $ product . map wins $ input print $ wins . join bimap (read . concatMap show) . unzip $ input
C++
Yesterday, I decided to code in Tcl. That program is still running, i will go back to the day 5 post once it finishes :)
Today was super simple. My first attempt worked in both cases, where the hardest part was really switching my ints to long longs. Part 1 worked on first compile and part 2 I had to compile twice after I realized the data type needs. Still, that change was made by search and replace.
I guess today was meant to be a real time race to get first answer? This is like day 1 stuff! Still, I have kids and a job so I did not get to stay up until the problem was posted.
I used C++ because I thought something intense may be coming on the part 2 problem, and I was burned yesterday. It looks like I spent another fast language on nothing! I think I’ll keep zig in the hole for the next number cruncher.
Oh, and yes my TCL program is still running…
My solutions can be found here:
// File: day-6a.cpp // Purpose: Solution to part of day 6 of advent of code in C++ // https://adventofcode.com/2023/day/6 // Author: Robert Lowe // Date: 6 December 2023 #include #include #include #include std::vector parse_line() { std::string line; std::size_t index; int num; std::vector result; // set up the stream std::getline(std::cin, line); index = line.find(':'); std::istringstream is(line.substr(index+1)); while(is>>num) { result.push_back(num); } return result; } int count_wins(int t, int d) { int count=0; for(int i=1; i d) { count++; } } return count; } int main() { std::vector time; std::vector dist; int product=1; // get the times and distances time = parse_line(); dist = parse_line(); // count the total number of wins for(auto titr=time.begin(), ditr=dist.begin(); titr!=time.end(); titr++, ditr++) { product *= count_wins(*titr, *ditr); } std::cout << product << std::endl; }
// File: day-6b.cpp // Purpose: Solution to part 2 of day 6 of advent of code in C++ // https://adventofcode.com/2023/day/6 // Author: Robert Lowe // Date: 6 December 2023 #include #include #include #include #include #include std::vector parse_line() { std::string line; std::size_t index; long long num; std::vector result; // set up the stream std::getline(std::cin, line); line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); index = line.find(':'); std::istringstream is(line.substr(index+1)); while(is>>num) { result.push_back(num); } return result; } long long count_wins(long long t, long long d) { long long count=0; for(long long i=1; i d) { count++; } } return count; } int main() { std::vector time; std::vector dist; long long product=1; // get the times and distances time = parse_line(); dist = parse_line(); // count the total number of wins for(auto titr=time.begin(), ditr=dist.begin(); titr!=time.end(); titr++, ditr++) { product *= count_wins(*titr, *ditr); } std::cout << product << std::endl; }
A nice change of pace from the previous puzzles, more maths and less parsing
Python
import math import re def create_table(filename: str) -> list[tuple[int, int]]: with open('day6.txt', 'r', encoding='utf-8') as file: times: list[str] = re.findall(r'\d+', file.readline()) distances: list[str] = re.findall(r'\d+', file.readline()) table: list[tuple[int, int]] = [] for t, d in zip(times, distances): table.append((int(t), int(d))) return table def get_possible_times_num(table_entry: tuple[int, int]) -> int: t, d = table_entry l_border: int = math.ceil(0.5 * (t - math.sqrt(t**2 -4 * d)) + 0.0000000000001) # Add small num to ensure you round up on whole numbers r_border: int = math.floor(0.5*(math.sqrt(t**2 - 4 * d) + t) - 0.0000000000001) # Subtract small num to ensure you round down on whole numbers return r_border - l_border + 1 def puzzle1() -> int: table: list[tuple[int, int]] = create_table('day6.txt') possibilities: int = 1 for e in table: possibilities *= get_possible_times_num(e) return possibilities def create_table_2(filename: str) -> tuple[int, int]: with open('day6.txt', 'r', encoding='utf-8') as file: t: str = re.search(r'\d+', file.readline().replace(' ', '')).group(0) d: str = re.search(r'\d+', file.readline().replace(' ', '')).group(0) return int(t), int(d) def puzzle2() -> int: t, d = create_table_2('day6.txt') return get_possible_times_num((t, d)) if __name__ == '__main__': print(puzzle1()) print(puzzle2())
Factor on github (with comments and imports):
I didn’t use any math smarts.
: input>data ( -- races ) "vocab:aoc-2023/day06/input.txt" utf8 file-lines [ ": " split harvest rest [ string>number ] map ] map first2 zip ; : go ( press-ms total-time -- distance ) over - * ; : beats-record? ( press-ms race -- ? ) [ first go ] [ last ] bi > ; : ways-to-beat ( race -- n ) dup first [1..b) [ over beats-record? ] map [ ] count nip ; : part1 ( -- ) input>data [ ways-to-beat ] map-product . ; : input>big-race ( -- race ) "vocab:aoc-2023/day06/input.txt" utf8 file-lines [ ":" split1 nip " " without string>number ] map ; : part2 ( -- ) input>big-race ways-to-beat . ;