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
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() } }
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
[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)
[Language: Lean4]
This one was straightforward, especially since Lean's Floats are 64bits. There is one interesting piece in the solution though, and that's the function that combines two integers, which I wrote because I want to use the same parse function for both parts. This
combineNumbers
function is interesting, because it needs a proof of termination to make the Lean4 compiler happy. Or, in other words, the compiler needs to be told that if n is larger than 0, n/10 is a strictly smaller integer than n. That proof actually exists in Lean's standard library, but the compiler doesn't find it by itself. Supplying it is as easy as invoking thesimp
tactic with that proof, and a proof that n is larger than 0.As with the previous days, I won't post the full source here, just the relevant parts. The full solution is on github, including the main function of the program, that loads the input file and runs the solution.
Solution
structure Race where timeLimit : Nat recordDistance : Nat deriving Repr private def parseLine (header : String) (input : String) : Except String (List Nat) := do if not $ input.startsWith header then throw s!"Unexpected line header: {header}, {input}" let input := input.drop header.length |> String.trim let numbers := input.split Char.isWhitespace |> List.map String.trim |> List.filter (not ∘ String.isEmpty) numbers.mapM $ Option.toExcept s!"Failed to parse input line: Not a number {input}" ∘ String.toNat? def parse (input : String) : Except String (List Race) := do let lines := input.splitOn "\n" |> List.map String.trim |> List.filter (not ∘ String.isEmpty) let (times, distances) ← match lines with | [times, distances] => let times ← parseLine "Time:" times let distances ← parseLine "Distance:" distances pure (times, distances) | _ => throw "Failed to parse: there should be exactly 2 lines of input" if times.length != distances.length then throw "Input lines need to have the same number of, well, numbers." let pairs := times.zip distances if pairs = [] then throw "Input does not have at least one race." return pairs.map $ uncurry Race.mk -- okay, part 1 is a quadratic equation. Simple as can be -- s = v * tMoving -- s = tPressed * (tLimit - tPressed) -- (tPressed - tLimit) * tPressed + s = 0 -- tPressed² - tPressed * tLimit + s = 0 -- tPressed := tLimit / 2 ± √(tLimit² / 4 - s) -- beware: We need to _beat_ the record, so s here is the record + 1 -- Inclusive! This is the smallest number that can win, and the largest number that can win private def Race.timeRangeToWin (input : Race) : (Nat × Nat) := let tLimit := input.timeLimit.toFloat let sRecord := input.recordDistance.toFloat let tlimitHalf := 0.5 * tLimit let theRoot := (tlimitHalf^2 - sRecord - 1.0).sqrt let lowerBound := tlimitHalf - theRoot let upperBound := tlimitHalf + theRoot let lowerBound := lowerBound.ceil.toUInt64.toNat let upperBound := upperBound.floor.toUInt64.toNat (lowerBound,upperBound) def part1 (input : List Race) : Nat := let limits := input.map Race.timeRangeToWin let counts := limits.map $ λ p ↦ p.snd - p.fst + 1 -- inclusive range counts.foldl (· * ·) 1 -- part2 is the same thing, but here we need to be careful. -- namely, careful about the precision of Float. Which luckily is enough, as confirmed by pen&paper -- but _barely_ enough. -- If Lean's Float were an actual C float and not a C double, this would not work. -- we need to concatenate the numbers again (because I don't want to make a separate parse for part2) private def combineNumbers (left : Nat) (right : Nat) : Nat := let rec countDigits := λ (s : Nat) (n : Nat) ↦ if p : n > 0 then have : n > n / 10 := by simp[p, Nat.div_lt_self] countDigits (s+1) (n/10) else s let d := if right = 0 then 1 else countDigits 0 right left * (10^d) + right def part2 (input : List Race) : Nat := let timeLimits := input.map Race.timeLimit let timeLimit := timeLimits.foldl combineNumbers 0 let records := input.map Race.recordDistance let record := records.foldl combineNumbers 0 let limits := Race.timeRangeToWin $ {timeLimit := timeLimit, recordDistance := record} limits.snd - limits.fst + 1 -- inclusive range open DayPart instance : Parse ⟨6, by simp⟩ (ι := List Race) where parse := parse instance : Part ⟨6, _⟩ Parts.One (ι := List Race) (ρ := Nat) where run := some ∘ part1 instance : Part ⟨6, _⟩ Parts.Two (ι := List Race) (ρ := Nat) where run := some ∘ part2
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 . ;
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..
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:
- https://github.com/pngwen/advent-2023/blob/main/day-6a.cpp
// 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; }
- https://github.com/pngwen/advent-2023/blob/main/day-6b.cpp
// 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; }
Scala3
// math.floor(i) == i if i.isWhole, but we want i-1 def hardFloor(d: Double): Long = (math.floor(math.nextAfter(d, Double.NegativeInfinity))).toLong def hardCeil(d: Double): Long = (math.ceil(math.nextAfter(d, Double.PositiveInfinity))).toLong def wins(t: Long, d: Long): Long = val det = math.sqrt(t*t/4.0 - d) val high = hardFloor(t/2.0 + det) val low = hardCeil(t/2.0 - det) (low to high).size def task1(a: List[String]): Long = def readLongs(s: String) = s.split(raw"\s+").drop(1).map(_.toLong) a match case List(s"Time: $time", s"Distance: $dist") => readLongs(time).zip(readLongs(dist)).map(wins).product case _ => 0L def task2(a: List[String]): Long = def readLong(s: String) = s.replaceAll(raw"\s+", "").toLong a match case List(s"Time: $time", s"Distance: $dist") => wins(readLong(time), readLong(dist)) case _ => 0L
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)
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
Today's problems felt really refreshing after yesterday.
Solution in Rust 🦀
Code
use std::{ collections::HashSet, env, fs, io::{self, BufRead, BufReader, Read}, }; fn main() -> io::Result<()> { let args: Vec = env::args().collect(); let filename = &args[1]; let file1 = fs::File::open(filename)?; let file2 = fs::File::open(filename)?; let reader1 = BufReader::new(file1); let reader2 = BufReader::new(file2); println!("Part one: {}", process_part_one(reader1)); println!("Part two: {}", process_part_two(reader2)); Ok(()) } fn parse_data(reader: BufReader) -> Vec> { let lines = reader.lines().flatten(); let data: Vec<_> = lines .map(|line| { line.split(':') .last() .expect("text after colon") .split_whitespace() .map(|s| s.parse::().expect("numbers")) .collect::>() }) .collect(); data } fn calculate_ways_to_win(time: u64, dist: u64) -> HashSet { let mut wins = HashSet::::new(); for t in 1..time { let d = t * (time - t); if d > dist { wins.insert(t); } } wins } fn process_part_one(reader: BufReader) -> u64 { let data = parse_data(reader); let results: Vec<_> = data[0].iter().zip(data[1].iter()).collect(); let mut win_method_qty: Vec = Vec::new(); for r in results { win_method_qty.push(calculate_ways_to_win(*r.0, *r.1).len() as u64); } win_method_qty.iter().product() } fn process_part_two(reader: BufReader) -> u64 { let data = parse_data(reader); let joined_data: Vec<_> = data .iter() .map(|v| { v.iter() .map(|d| d.to_string()) .collect::>() .join("") .parse::() .expect("all digits") }) .collect(); calculate_ways_to_win(joined_data[0], joined_data[1]).len() as u64 } #[cfg(test)] mod tests { use super::*; const INPUT: &str = "Time: 7 15 30 Distance: 9 40 200"; #[test] fn test_process_part_one() { let input_bytes = INPUT.as_bytes(); assert_eq!(288, process_part_one(BufReader::new(input_bytes))); } #[test] fn test_process_part_two() { let input_bytes = INPUT.as_bytes(); assert_eq!(71503, process_part_two(BufReader::new(input_bytes))); } }
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 :(
That was so much better than yesterday. Went with algebra but looks like brute force would have worked.
python
import re import argparse import math # i feel doing this with equations is probably the # "fast" way. # we can re-arange stuff so we only need to find the point # the line crosses the 0 line # distance is speed * (time less time holding the button (which is equal to speed)): # -> d = v * (t - v) # -> v^2 -vt +d = 0 # -> y=0 @ v = t +- sqrt( t^2 - 4d) / 2 def get_cross_points(time:int, distance:int) -> list | None: pre_root = time**2 - (4 * distance) if pre_root < 0: # no solutions return None if pre_root == 0: # one solution return [(float(time)/2)] sqroot = math.sqrt(pre_root) v1 = (float(time) + sqroot)/2 v2 = (float(time) - sqroot)/2 return [v1,v2] def float_pair_to_int_pair(a:float,b:float): # if floats are equal to int value, then we need to add one to value # as we are looking for values above 0 point if a > b: # lower a and up b if a == int(a): a -= 1 if b == int(b): b += 1 return [math.floor(a),math.ceil(b)] if a < b: if a == int(a): a += 1 if b == int(b): b -= 1 return [math.floor(b),math.ceil(a)] def main(line_list: list): time_section,distance_section = line_list if (args.part == 1): time_list = filter(None , re.split(' +',time_section.split(':')[1])) distance_list = filter(None , re.split(' +',distance_section.split(':')[1])) games = list(zip(time_list,distance_list)) if (args.part == 2): games = [ [time_section.replace(' ','').split(':')[1],distance_section.replace(' ','').split(':')[1]] ] print (games) total = 1 for t,d in games: cross = get_cross_points(int(t),int(d)) cross_int = float_pair_to_int_pair(*cross) print (cross_int) total *= cross_int[0] - cross_int[1] +1 print(f"total: {total}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="day 6 solver") parser.add_argument("-input",type=str) parser.add_argument("-part",type=int) args = parser.parse_args() filename = args.input if filename == None: parser.print_help() exit(1) file = open(filename,'r') main([line.rstrip('\n') for line in file.readlines()]) file.close()