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
Rust
I went with solving the quadratic equation, so part 2 was just a trivial change in parsing. It was a bit janky to find the integer that is strictly larger than a floating point number, but it all worked out.
I wanted to try the easy approach first and see how slow it was. Didn’t even take a second for part 2. So I just skipped the mathematical solution entirely.
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 $ inputNim
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.
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())deleted by creator
A nice simple one today. And only a half second delay for part two instead of half an hour. What a treat. I could probably have nicer input parsing, but that seems to be the theme this year, so that will become a big focus of my next round through these I’m guessing. The algorithm here to get the winning possibilities could also probably be improved upon by figuring out what the number of seconds for the current record is, and only looping from there until hitting a number that doesn’t win, as opposed to brute-forcing the whole loop.
https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day06.rs
#[derive(Debug)] struct Race { time: u64, distance: u64, } impl Race { fn possible_ways_to_win(&self) -> usize { (0..=self.time) .filter(|time| time * (self.time - time) > self.distance) .count() } } pub struct Day06; impl Solver for Day06 { fn star_one(&self, input: &str) -> String { let mut race_data = input .lines() .map(|line| { line.split_once(':') .unwrap() .1 .split_ascii_whitespace() .filter_map(|number| number.parse::().ok()) .collect::>() }) .collect::>(); let times = race_data.pop().unwrap(); let distances = race_data.pop().unwrap(); let races = distances .into_iter() .zip(times) .map(|(time, distance)| Race { time, distance }) .collect::>(); races .iter() .map(|race| race.possible_ways_to_win()) .fold(1, |acc, count| acc * count) .to_string() } fn star_two(&self, input: &str) -> String { let race_data = input .lines() .map(|line| { line.split_once(':') .unwrap() .1 .replace(" ", "") .parse::() .unwrap() }) .collect::>(); let race = Race { time: race_data[0], distance: race_data[1], }; race.possible_ways_to_win().to_string() } }C
Brute forced it, runs in 60 ms or so. Only shortcut is quitting the loop when the distance drops below the record. I didn’t bother with the closed form solution here because a) it ran so fast and b) I was concerned about floats, rounding and off-by-one errors. Will probably implement it later!
Edit: implemented the closed form solution. Feels dirty copying a formula without really understanding it…
Should you be using
SCNi64instead ofPRIi64insscanf?Yes, thank you!
My solutions, as always, in C: https://git.sr.ht/~aidenisik/aoc23/tree/master/item/day6
It’s nice that the bruteforce method doesn’t take HOURS for this one. My day 5 bruteforce is still running :(
Rust:
For part 2, all I did was edit the input and change
i32toi64.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) }Python
Questions and feedback welcome!
import re from functools import reduce from operator import mul from .solver import Solver def upper_bound(start: int, stop: int, predicate: Callable[[int], bool]) -> int: """Find the smallest integer in [start, stop) for which the predicate is false, or stop if the predicate is always true. The predicate must be monotonic, i.e. predicate(x + 1) implies predicate(x). """ assert start < stop if not predicate(start): return start if predicate(stop - 1): return stop while start + 1 < stop: mid = (start + stop) // 2 if predicate(mid): start = mid else: stop = mid return stop def travel_distance(hold: int, limit: int) -> int: dist = hold * (limit - hold) return dist def ways_to_win(time: int, record: int) -> int: definitely_winning_hold = time // 2 assert travel_distance(definitely_winning_hold, time) > record minimum_hold_to_win = upper_bound( 1, definitely_winning_hold, lambda hold: travel_distance(hold, time) <= record) minimum_hold_to_lose = upper_bound( definitely_winning_hold, time, lambda hold: travel_distance(hold, time) > record) return minimum_hold_to_lose - minimum_hold_to_win class Day06(Solver): def __init__(self): super().__init__(6) self.times = [] self.distances = [] def presolve(self, input: str): times, distances = input.rstrip().split('\n') self.times = [int(time) for time in re.split(r'\s+', times)[1:]] self.distances = [int(distance) for distance in re.split(r'\s+', distances)[1:]] def solve_first_star(self): ways= [] for time, record in zip(self.times, self.distances): ways.append(ways_to_win(time, record)) return reduce(mul, ways) def solve_second_star(self): time = int(''.join(map(str, self.times))) distance = int(''.join(map(str, self.distances))) return ways_to_win(time, distance)[JavaScript] Relatively easy one today
Part 1
function part1(input) { const split = input.split("\n"); const times = split[0].match(/\d+/g).map((x) => parseInt(x)); const distances = split[1].match(/\d+/g).map((x) => parseInt(x)); let sum = 0; for (let i = 0; i < times.length; i++) { const time = times[i]; const recordDistance = distances[i]; let count = 0; for (let j = 0; j < time; j++) { const timePressed = j; const remainingTime = time - j; const travelledDistance = timePressed * remainingTime; if (travelledDistance > recordDistance) { count++; } } if (sum == 0) { sum = count; } else { sum = sum * count; } } return sum; }Part 2
function part2(input) { const split = input.split("\n"); const time = parseInt(split[0].split(":")[1].replace(/\s/g, "")); const recordDistance = parseInt(split[1].split(":")[1].replace(/\s/g, "")); let count = 0; for (let j = 0; j < time; j++) { const timePressed = j; const remainingTime = time - j; const travelledDistance = timePressed * remainingTime; if (travelledDistance > recordDistance) { count++; } } return count; }Was a bit late with posting the solution thread and solving this since I ended up napping until 2am, if anyone notices theres no solution thread and its after the leaderboard has been filled (can check from the stats page if 100 people are done) feel free to start one up (I just copy paste the text in each of them)
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 }Golang
Pretty straightforward. The only optimization I did is that the pairs are symmetric (3ms hold and 4ms travel is the same as 4ms hold and 3ms travel).
Part 1
file, _ := os.Open("input.txt") defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() times := strings.Fields(strings.Split(scanner.Text(), ":")[1]) scanner.Scan() distances := strings.Fields(strings.Split(scanner.Text(), ":")[1]) n := len(times) countProduct := 1 for i := 0; i < n; i++ { t, _ := strconv.Atoi(times[i]) d, _ := strconv.Atoi(distances[i]) count := 0 for j := 0; j <= t/2; j++ { if j*(t-j) > d { if t%2 == 0 && j == t/2 { count++ } else { count += 2 } } } countProduct *= count } fmt.Println(countProduct)Part 2
file, _ := os.Open("input.txt") defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() time := strings.ReplaceAll(strings.Split(scanner.Text(), ":")[1], " ", "") scanner.Scan() distance := strings.ReplaceAll(strings.Split(scanner.Text(), ":")[1], " ", "") t, _ := strconv.Atoi(time) d, _ := strconv.Atoi(distance) count := 0 for j := 0; j <= t/2; j++ { if j*(t-j) > d { if t%2 == 0 && j == t/2 { count++ } else { count += 2 } } } fmt.Println(count)ah damn, didn’t think of the symmetric pairs
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; }Not sure if it’s the most optimal, but I figured it’s probably quicker to calculate the first point when you start winning, and then reverse it to get the last point when you’ll last win. Subtracting the two to get the total number of ways to win.
Takes about 3 seconds to run on the real input
Python Solution
class Race: def __init__(self, time, distance): self.time = time self.distance = distance def get_win(self, start, stop, step): for i in range(start, stop, step): if (self.time - i) * i > self.distance: return i def get_winners(self): return ( self.get_win(0, self.time, 1), self.get_win(self.time, 0, -1), ) race = Race(71530, 940200) winners = race.get_winners() print(winners[1] - winners[0] + 1)Crystal
# part 1 times = input[0][5..].split.map &.to_i dists = input[1][9..].split.map &.to_i prod = 1 times.each_with_index do |time, i| start, last = find_poss(time, dists[i]) prod *= last - start + 1 end puts prod # part 2 time = input[0][5..].chars.reject!(' ').join.to_i64 dist = input[1][9..].chars.reject!(' ').join.to_i64 start, last = find_poss(time, dist) puts last - start + 1 def find_poss(time, dist) start = 0 last = 0 (1...time).each do |acc_time| if (time-acc_time)*acc_time > dist start = acc_time break end end (1...time).reverse_each do |acc_time| if (time-acc_time)*acc_time > dist last = acc_time break end end {start, last} end











