🌟 - 2023 DAY 6 SOLUTIONS -🌟

# 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 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

Adanisi,
@Adanisi@lemmy.zip avatar

My solutions, as always, in C: 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 :(

soulsource,
@soulsource@discuss.tchncs.de avatar

[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 the simp 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.

SolutionLean4 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

morrowind,
@morrowind@lemmy.ml avatar

Crystal


<span style="color:#323232;"># part 1
</span><span style="color:#323232;">times = input[0][5..].split.map &.to_i
</span><span style="color:#323232;">dists = input[1][9..].split.map &.to_i
</span><span style="color:#323232;">
</span><span style="color:#323232;">prod = 1
</span><span style="color:#323232;">times.each_with_index do |time, i|
</span><span style="color:#323232;">	start, last = find_poss(time, dists[i])
</span><span style="color:#323232;">	prod *= last - start + 1
</span><span style="color:#323232;">end
</span><span style="color:#323232;">puts prod
</span><span style="color:#323232;">
</span><span style="color:#323232;"># part 2
</span><span style="color:#323232;">time = input[0][5..].chars.reject!(' ').join.to_i64
</span><span style="color:#323232;">dist = input[1][9..].chars.reject!(' ').join.to_i64
</span><span style="color:#323232;">
</span><span style="color:#323232;">start, last = find_poss(time, dist)
</span><span style="color:#323232;">puts last - start + 1
</span><span style="color:#323232;">
</span><span style="color:#323232;">def find_poss(time, dist)
</span><span style="color:#323232;">	start = 0
</span><span style="color:#323232;">	last  = 0
</span><span style="color:#323232;">	(1...time).each do |acc_time|
</span><span style="color:#323232;">		if (time-acc_time)*acc_time > dist
</span><span style="color:#323232;">			start = acc_time
</span><span style="color:#323232;">			break
</span><span style="color:#323232;">	end     end
</span><span style="color:#323232;">	(1...time).reverse_each do |acc_time|
</span><span style="color:#323232;">		if (time-acc_time)*acc_time > dist
</span><span style="color:#323232;">			last = acc_time
</span><span style="color:#323232;">			break
</span><span style="color:#323232;">	end     end
</span><span style="color:#323232;">	{start, last}
</span><span style="color:#323232;">end
</span>
bamboo,

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 Solutionclass 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)

vole, (edited )

Raku

I spent a lot more time than necessary optimizing the count-ways-to-beat function, but I’m happy with the result. This is my first time using the | operator to flatten a list into function arguments.

edit: unfortunately, the lemmy web page is unable to properly display the source code in a code block. It doesn’t display text enclosed in pointy brackets <>, perhaps it looks too much like HTML. View code on github.

Coderaku use v6; sub MAIN($input) { my $file = open $input; grammar Records { token TOP { “n” “n”* } token times { “Time:” s* +%s+ } token distances { “Distance:” s* +%s+ } token num { d+ } } my $records = Records.parse($file.slurp); my $part-one-solution = 1; for $records».Int Z $records».Int -> $record { $part-one-solution *= count-ways-to-beat(|$record); } say “part 1: $part-one-solution”; my $kerned-time = $records.join.Int; my $kerned-distance = $records.join.Int; my $part-two-solution = count-ways-to-beat($kerned-time, $kerned-distance); say “part 2: $part-two-solution”; } sub count-ways-to-beat($time, $record-distance) { # time = button + go # distance = go * button # 0 = go^2 - time * go + distance # go = (time +/- sqrt(time**2 - 4*distance))/2 # don’t think too hard: # if odd t then t/2 = x.5, # so sqrt(t**2-4*d)/2 = 2.3 => result = 4 # and sqrt(t**2-4*d)/2 = 2.5 => result = 6 # therefore result = 2 * (sqrt(t**2-4*d)/2 + 1/2).floor # even t then t/2 = x.0 # so sqrt(t^2-4*d)/2 = 2.x => result = 4 + 1(shared) = 5 # therefore result = 2 * (sqrt(t^2-4*d)/2).floor + 1 # therefore result = 2 * ((sqrt(t**2-4*d)+t%2)/2).floor + 1 - t%2 # Note: sqrt produces a Num, so perhaps the result could be off by 1 or 2, # but it solved my AoC inputs correctly 😃. my $required-distance = $record-distance + 1; return 2 * ((sqrt($time**2 - 4*$required-distance) + $time%2)/2).floor + 1 - $time%2; }

pngwen,

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:


<span style="color:#323232;">// File: day-6a.cpp
</span><span style="color:#323232;">// Purpose: Solution to part of day 6 of advent of code in C++
</span><span style="color:#323232;">//          https://adventofcode.com/2023/day/6
</span><span style="color:#323232;">// Author: Robert Lowe
</span><span style="color:#323232;">// Date: 6 December 2023
</span><span style="color:#323232;">#include <iostream>
</span><span style="color:#323232;">#include <vector>
</span><span style="color:#323232;">#include <string>
</span><span style="color:#323232;">#include <sstream>
</span><span style="color:#323232;">
</span><span style="color:#323232;">std::vector<int> parse_line()
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    std::string line;
</span><span style="color:#323232;">    std::size_t index;
</span><span style="color:#323232;">    int num;
</span><span style="color:#323232;">    std::vector<int> result;
</span><span style="color:#323232;">    
</span><span style="color:#323232;">    // set up the stream
</span><span style="color:#323232;">    std::getline(std::cin, line);
</span><span style="color:#323232;">    index = line.find(':');
</span><span style="color:#323232;">    std::istringstream is(line.substr(index+1));
</span><span style="color:#323232;">
</span><span style="color:#323232;">    while(is>>num) {
</span><span style="color:#323232;">        result.push_back(num);
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    return result;
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">int count_wins(int t, int d) 
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    int count=0;
</span><span style="color:#323232;">    for(int i=1; i<t; i++) {
</span><span style="color:#323232;">        if(t*i-i*i > d) {
</span><span style="color:#323232;">            count++;
</span><span style="color:#323232;">        }
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">    return count;
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">int main()
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    std::vector<int> time;
</span><span style="color:#323232;">    std::vector<int> dist;
</span><span style="color:#323232;">    int product=1;
</span><span style="color:#323232;">
</span><span style="color:#323232;">    // get the times and distances
</span><span style="color:#323232;">    time = parse_line();
</span><span style="color:#323232;">    dist = parse_line();
</span><span style="color:#323232;">
</span><span style="color:#323232;">    // count the total number of wins
</span><span style="color:#323232;">    for(auto titr=time.begin(), ditr=dist.begin(); titr!=time.end(); titr++, ditr++) {
</span><span style="color:#323232;">        product *= count_wins(*titr, *ditr);
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    std::cout << product << std::endl;
</span><span style="color:#323232;">}
</span>

<span style="color:#323232;">// File: day-6b.cpp
</span><span style="color:#323232;">// Purpose: Solution to part 2 of day 6 of advent of code in C++
</span><span style="color:#323232;">//          https://adventofcode.com/2023/day/6
</span><span style="color:#323232;">// Author: Robert Lowe
</span><span style="color:#323232;">// Date: 6 December 2023
</span><span style="color:#323232;">#include <iostream>
</span><span style="color:#323232;">#include <vector>
</span><span style="color:#323232;">#include <string>
</span><span style="color:#323232;">#include <sstream>
</span><span style="color:#323232;">#include <algorithm>
</span><span style="color:#323232;">#include <cctype>
</span><span style="color:#323232;">
</span><span style="color:#323232;">std::vector<long long> parse_line()
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    std::string line;
</span><span style="color:#323232;">    std::size_t index;
</span><span style="color:#323232;">    long long num;
</span><span style="color:#323232;">    std::vector<long long> result;
</span><span style="color:#323232;">    
</span><span style="color:#323232;">    // set up the stream
</span><span style="color:#323232;">    std::getline(std::cin, line);
</span><span style="color:#323232;">    line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());
</span><span style="color:#323232;">    index = line.find(':');
</span><span style="color:#323232;">    std::istringstream is(line.substr(index+1));
</span><span style="color:#323232;">
</span><span style="color:#323232;">    while(is>>num) {
</span><span style="color:#323232;">        result.push_back(num);
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    return result;
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">long long count_wins(long long t, long long d) 
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    long long count=0;
</span><span style="color:#323232;">    for(long long i=1; i<t; i++) {
</span><span style="color:#323232;">        if(t*i-i*i > d) {
</span><span style="color:#323232;">            count++;
</span><span style="color:#323232;">        }
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">    return count;
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">int main()
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    std::vector<long long> time;
</span><span style="color:#323232;">    std::vector<long long> dist;
</span><span style="color:#323232;">    long long product=1;
</span><span style="color:#323232;">
</span><span style="color:#323232;">    // get the times and distances
</span><span style="color:#323232;">    time = parse_line();
</span><span style="color:#323232;">    dist = parse_line();
</span><span style="color:#323232;">
</span><span style="color:#323232;">    // count the total number of wins
</span><span style="color:#323232;">    for(auto titr=time.begin(), ditr=dist.begin(); titr!=time.end(); titr++, ditr++) {
</span><span style="color:#323232;">        product *= count_wins(*titr, *ditr);
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    std::cout << product << std::endl;
</span><span style="color:#323232;">}
</span>
capitalpb,

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.

github.com/capitalpb/…/day06.rs


<span style="color:#323232;">#[derive(Debug)]
</span><span style="font-weight:bold;color:#a71d5d;">struct </span><span style="color:#323232;">Race {
</span><span style="color:#323232;">    time: </span><span style="font-weight:bold;color:#a71d5d;">u64</span><span style="color:#323232;">,
</span><span style="color:#323232;">    distance: </span><span style="font-weight:bold;color:#a71d5d;">u64</span><span style="color:#323232;">,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">impl </span><span style="color:#323232;">Race {
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">possible_ways_to_win</span><span style="color:#323232;">(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;self) -> </span><span style="font-weight:bold;color:#a71d5d;">usize </span><span style="color:#323232;">{
</span><span style="color:#323232;">        (</span><span style="color:#0086b3;">0</span><span style="font-weight:bold;color:#a71d5d;">..=</span><span style="color:#323232;">self.time)
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">filter</span><span style="color:#323232;">(|time| time </span><span style="font-weight:bold;color:#a71d5d;">* </span><span style="color:#323232;">(self.time </span><span style="font-weight:bold;color:#a71d5d;">-</span><span style="color:#323232;"> time) </span><span style="font-weight:bold;color:#a71d5d;">> </span><span style="color:#323232;">self.distance)
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">count</span><span style="color:#323232;">()
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">pub struct </span><span style="color:#323232;">Day06;
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">impl </span><span style="color:#323232;">Solver </span><span style="font-weight:bold;color:#a71d5d;">for </span><span style="color:#323232;">Day06 {
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">star_one</span><span style="color:#323232;">(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;self, input: </span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;</span><span style="font-weight:bold;color:#a71d5d;">str</span><span style="color:#323232;">) -> String {
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let mut</span><span style="color:#323232;"> race_data </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> input
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">lines</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|line| {
</span><span style="color:#323232;">                line.</span><span style="color:#62a35c;">split_once</span><span style="color:#323232;">(</span><span style="color:#183691;">':'</span><span style="color:#323232;">)
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">()
</span><span style="color:#323232;">                    .</span><span style="color:#0086b3;">1
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">split_ascii_whitespace</span><span style="color:#323232;">()
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">filter_map</span><span style="color:#323232;">(|number| number.parse::().</span><span style="color:#62a35c;">ok</span><span style="color:#323232;">())
</span><span style="color:#323232;">                    .collect::</span><span style="font-weight:bold;color:#a71d5d;">></span><span style="color:#323232;">()
</span><span style="color:#323232;">            })
</span><span style="color:#323232;">            .collect::</span><span style="font-weight:bold;color:#a71d5d;">></span><span style="color:#323232;">();
</span><span style="color:#323232;">
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> times </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> race_data.</span><span style="color:#62a35c;">pop</span><span style="color:#323232;">().</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">();
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> distances </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> race_data.</span><span style="color:#62a35c;">pop</span><span style="color:#323232;">().</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">();
</span><span style="color:#323232;">
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> races </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> distances
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">into_iter</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">zip</span><span style="color:#323232;">(times)
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|(time, distance)| Race { time, distance })
</span><span style="color:#323232;">            .collect::</span><span style="font-weight:bold;color:#a71d5d;">></span><span style="color:#323232;">();
</span><span style="color:#323232;">
</span><span style="color:#323232;">        races
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">iter</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|race| race.</span><span style="color:#62a35c;">possible_ways_to_win</span><span style="color:#323232;">())
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">fold</span><span style="color:#323232;">(</span><span style="color:#0086b3;">1</span><span style="color:#323232;">, |acc, count| acc </span><span style="font-weight:bold;color:#a71d5d;">*</span><span style="color:#323232;"> count)
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">to_string</span><span style="color:#323232;">()
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">star_two</span><span style="color:#323232;">(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;self, input: </span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;</span><span style="font-weight:bold;color:#a71d5d;">str</span><span style="color:#323232;">) -> String {
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> race_data </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> input
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">lines</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|line| {
</span><span style="color:#323232;">                line.</span><span style="color:#62a35c;">split_once</span><span style="color:#323232;">(</span><span style="color:#183691;">':'</span><span style="color:#323232;">)
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">()
</span><span style="color:#323232;">                    .</span><span style="color:#0086b3;">1
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">replace</span><span style="color:#323232;">(</span><span style="color:#183691;">" "</span><span style="color:#323232;">, </span><span style="color:#183691;">""</span><span style="color:#323232;">)
</span><span style="color:#323232;">                    .parse::()
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">()
</span><span style="color:#323232;">            })
</span><span style="color:#323232;">            .collect::</span><span style="font-weight:bold;color:#a71d5d;">></span><span style="color:#323232;">();
</span><span style="color:#323232;">
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> race </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> Race {
</span><span style="color:#323232;">            time: race_data[</span><span style="color:#0086b3;">0</span><span style="color:#323232;">],
</span><span style="color:#323232;">            distance: race_data[</span><span style="color:#0086b3;">1</span><span style="color:#323232;">],
</span><span style="color:#323232;">        };
</span><span style="color:#323232;">
</span><span style="color:#323232;">        race.</span><span style="color:#62a35c;">possible_ways_to_win</span><span style="color:#323232;">().</span><span style="color:#62a35c;">to_string</span><span style="color:#323232;">()
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">}
</span>
mykl, (edited )
@mykl@lemmy.world avatar

Today was easy enough that I felt confident that I could hammer out a solution in Uiua, so read and enjoy (or try it out live):


<span style="color:#323232;">{"Time:      7  15   30"
</span><span style="color:#323232;"> "Distance:  9  40  200"}
</span><span style="color:#323232;">StoInt ← /(+ ×10) ▽×⊃(≥0)(≤9). -@0
</span><span style="color:#323232;">Count ← (
</span><span style="color:#323232;">  ⊙⊢√-×4:×.⍘⊟.           # Determinant, and time
</span><span style="color:#323232;">  +1-⊃(+1↥0⌊÷2-)(-1⌈÷2+) # Diff of sanitised roots
</span><span style="color:#323232;">)
</span><span style="color:#323232;">≡(↘1⊐⊜∘≠@s.)
</span><span style="color:#323232;">⊃(/×≡Count⍉∵StoInt)(Count⍉≡(StoInt⊐/⊂))
</span>
reboot6675,

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 1file, _ := 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 &lt; n; i++ { t, _ := strconv.Atoi(times[i]) d, _ := strconv.Atoi(distances[i]) count := 0 for j := 0; j &lt;= t/2; j++ { if j*(t-j) > d { if t%2 == 0 &amp;&amp; j == t/2 { count++ } else { count += 2 } } } countProduct *= count } fmt.Println(countProduct)

Part 2file, _ := 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 &lt;= t/2; j++ { if j*(t-j) > d { if t%2 == 0 &amp;&amp; j == t/2 { count++ } else { count += 2 } } } fmt.Println(count)

morrowind,
@morrowind@lemmy.ml avatar

ah damn, didn’t think of the symmetric pairs

bugsmith,
@bugsmith@programming.dev avatar

Today’s problems felt really refreshing after yesterday.

Solution in Rust 🦀

View formatted code on GitLab

Coderust use std::{ collections::HashSet, env, fs, io::{self, BufRead, BufReader, Read}, }; fn main() -> io::Result&lt;()> { let args: Vec = env::args().collect(); let filename = &amp;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&lt;_> = 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&lt;_> = 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&lt;_> = 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: &amp;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))); } }

Gobbel2000,
@Gobbel2000@feddit.de avatar

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.

frugally,

(number+1).floor() does the trick

Gobbel2000,
@Gobbel2000@feddit.de avatar

Oh yeah, that’s clever. I’ll remember that when it comes up again.

moriquende,

In Python when using numpy to find the roots, sometimes you get a numeric artifact like 30.99999999999, which breaks this. Make sure to limit the significant digits to a sane amount like 5 with rounding to prevent that.

Black616Angel,

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.

pnutzh4x0r,
@pnutzh4x0r@lemmy.ndlug.org avatar

Language: Python

Part 1Not much to say… this was pretty straightforward. def race(charge_time: int, total_time: int) -> int: return charge_time * (total_time - charge_time) def main(stream=sys.stdin) -> None: times = [int(t) for t in stream.readline().split(‘:’)[-1].split()] distances = [int(d) for d in stream.readline().split(‘:’)[-1].split()] product = 1 for time, distance in zip(times, distances): ways = [c for c in range(1, time + 1) if race(c, time) > distance] product *= len(ways) print(product)

Part 2Probably could have done some math, but didn’t need to :] def race(charge_time: int, total_time: int): return charge_time * (total_time - charge_time) def main(stream=sys.stdin) -> None: time = int(‘’.join(stream.readline().split(‘:’)[-1].split())) distance = int(‘’.join(stream.readline().split(‘:’)[-1].split())) ways = [c for c in range(1, time + 1) if race(c, time) > distance] print(len(ways))

GitHub Repo

purplemonkeymad,

That was so much better than yesterday. Went with algebra but looks like brute force would have worked.

pythonimport 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()

janAkali, (edited )

Nim

Today’s puzzle was too easy. I solved it with bruteforce in 20 minutes, but that’s boring. So here’s the optimized solution with quadratic formula.

Total runtime: 0.008 ms
Puzzle rating: Too Easy 5/10
Code: day_06/solution.nim

cvttsd2si,

Scala3


<span style="color:#323232;">// math.floor(i) == i if i.isWhole, but we want i-1
</span><span style="color:#323232;">def hardFloor(d: Double): Long = (math.floor(math.nextAfter(d, Double.NegativeInfinity))).toLong
</span><span style="color:#323232;">def hardCeil(d: Double): Long = (math.ceil(math.nextAfter(d, Double.PositiveInfinity))).toLong
</span><span style="color:#323232;">
</span><span style="color:#323232;">def wins(t: Long, d: Long): Long =
</span><span style="color:#323232;">    val det = math.sqrt(t*t/4.0 - d)
</span><span style="color:#323232;">    val high = hardFloor(t/2.0 + det)
</span><span style="color:#323232;">    val low = hardCeil(t/2.0 - det)
</span><span style="color:#323232;">    (low to high).size
</span><span style="color:#323232;">
</span><span style="color:#323232;">def task1(a: List[String]): Long = 
</span><span style="color:#323232;">    def readLongs(s: String) = s.split(raw"s+").drop(1).map(_.toLong)
</span><span style="color:#323232;">    a match
</span><span style="color:#323232;">        case List(s"Time: $time", s"Distance: $dist") => readLongs(time).zip(readLongs(dist)).map(wins).product
</span><span style="color:#323232;">        case _ => 0L
</span><span style="color:#323232;">
</span><span style="color:#323232;">def task2(a: List[String]): Long =
</span><span style="color:#323232;">    def readLong(s: String) = s.replaceAll(raw"s+", "").toLong
</span><span style="color:#323232;">    a match
</span><span style="color:#323232;">        case List(s"Time: $time", s"Distance: $dist") => wins(readLong(time), readLong(dist))
</span><span style="color:#323232;">        case _ => 0L
</span>
  • All
  • Subscribed
  • Moderated
  • Favorites
  • advent_of_code@programming.dev
  • kavyap
  • thenastyranch
  • ethstaker
  • DreamBathrooms
  • osvaldo12
  • magazineikmin
  • tacticalgear
  • Youngstown
  • everett
  • mdbf
  • slotface
  • ngwrru68w68
  • rosin
  • Durango
  • JUstTest
  • InstantRegret
  • GTA5RPClips
  • tester
  • cubers
  • cisconetworking
  • normalnudes
  • khanakhh
  • modclub
  • anitta
  • Leos
  • megavids
  • provamag3
  • lostlight
  • All magazines