RagingHungryPanda

joined 2 years ago
[โ€“] [email protected] 1 points 8 months ago

I had to borrow some of y'alls code to finish part 2. My approach and all the attempts I did at trying to get the slopes of lines and such couldn't get it high enough.

I thought to move from the prize along it's furthest away axis until I got to the intersection of the slope of the two buttons.

I thought that maybe that wasn't the cheapest way, so I fiddled around with the order of button A and B, but still couldn't get it high enough.

It looks like this group was mostly doing the cross product of the prize to the two buttons. I'm too dumb to realize how that would work. I thought you'd want to move along the furthest away axis first, but maybe it doesn't matter.

If anyone can see if I did anything obviously wrong, I'd appreciate it. I normally don't like to take code without fixing whatever it is I was doing since it always bites me in the butt later, but here I am.

F#

expand for source

let getButtonCounts (buttonA: Button) (buttonB: Button) buttonACost buttonBCost (prize:Prize) =
    // my way of trying to solve by moving the greatest axis first doesn't work for part 2.
    // everyone else seems to be using the slope between the two buttons and applying the cost
    // to a part. I don't see how it works but fuck it.
    // I had to add the `abs` calls to a and b to the borrow code, so who knows wtf. I'm done.
    let cpAB = crossProduct buttonA buttonB
    if cpAB = 0 then None
    else
        let detA = crossProduct prize buttonB
        let detB = crossProduct prize buttonA
        let struct(a, rem_a) = Int64.DivRem(detA, cpAB)
        let struct(b, rem_b) = Int64.DivRem(detB, cpAB)
        if (rem_a <> 0 || rem_b <> 0) then None
        else (abs(a) * (int64 buttonACost) + abs(b)) |> Some
    
    
    // here's where my code was. It came up short on part 2
    let (majorAxis:Point2<int64> -> int64), (minorAxis:Point2<int64> -> int64) = if prize.X > prize.Y then _.X, _.Y else _.Y,_.X
    let firstButton,firstCost, secondButton,secondCost =
        if majorAxis buttonA = majorAxis buttonB then (buttonB, buttonBCost, buttonA, buttonACost)
        else if majorAxis buttonA > majorAxis buttonB then (buttonA,buttonACost, buttonB,buttonBCost)
        else (buttonB, buttonBCost, buttonA, buttonACost)
    
    let origin:Point2<int64> = {X = 0; Y = 0}
    let toSlope button  = Segment.Slope.findL {Start = origin; End = button}
    
    let majorLine = (toSlope firstButton) |> fun s -> {Point = prize; Slope = s }
    let minorLine = (toSlope secondButton) |> fun s -> {Point = origin; Slope = s}
    
    let minorOffset = {Point = secondButton; Slope = minorLine.Slope }
    let intersection = Line.intersection majorLine minorOffset
                       |> Option.filter intersectsOnWholeNumber
                       // |> Option.filter (fun i -> i.X <= (float prize.X) && i.Y <= (float prize.Y)) // is in bounds
                       |> Option.map(fun p ->
                           let pp:Point2<int64> = {X = p.X |> round |> int64; Y = p.Y |> round |> int64}
                           pp)
                       // comparing by slopes can intersect outside of the bounds
                       // of the prize, which is not compatible
    
    match intersection with
    | None -> None
    | Some i -> 
        // steps to move to intersection
        let firstMovement =  (majorAxis prize - majorAxis i) / (majorAxis firstButton)
        // steps to move to 0
        let secondMovement = (minorAxis i) / (minorAxis secondButton)
        
        let cost = firstMovement * (int64 firstCost) + secondMovement * (int64 secondCost)
        Some cost

[โ€“] [email protected] 2 points 8 months ago

hey thanks!

I didn't check any other solutions before finishing (currently wondering way day 13 is too low), but I thought that trying to traverse fences would be a pain and since I have everything separated by regions and not traversing the array, counting corners never came to mind.

But the thought that I had was that for each region, all points will be a straight line in the V or H orientations, so if I can go up and down and count when last != next - 1, then that'll tell me that that is a contiguous piece of fence.

The idea isn't too hard, for tracking the XAxis it's

region.GroupBy(YAxis) // row
.Select(group => 
    group.Sort(g => g.XAxis) // column
        .Window(a,b => a != b - 1 ? 1 : 0).Sum()
.Sum()

Except that I used a different splitting method and that came to me later.

[โ€“] [email protected] 2 points 8 months ago* (last edited 8 months ago) (2 children)

I know I'm late, but it's still fun and I'm sure no-one will see this.

Part 2 took me way too long to get right. I was initially only returning the relative point to which a plot needed a fence. I ran into issues of knowing if it was a valid fence or not by my method of counting (later). I eventually went with returning a tuple of the plot and an enum flag of the sides that it has fences on.

For counting I grouped the points by one axis then sorted on the other and counted the number of times the transition between two wasn't contiguous.

It could by done in parallel, but the original traversal would need de-duping, which I didn't feel like doing. After that things are done on a region basis, which could be parallel.

I also can't help but notice mine is by far the longest ( > . < )

F#

Tap for spoiler

type Plant = char
type Plot = Plant * Point2I
type Region = Plot list

let area region = List.length region

let perimeter (region:Region) (farm:Grid<Plant>) =
    (0, region)
    ||> List.fold (fun sum plot ->
        movements4 (snd plot) farm
        |> List.fold (fun acc po ->
            acc + match po with
                  | ValueNone -> 1
                  | ValueSome pother ->
                      get pother farm
                      |> fun x ->
                          match x with
                          | ValueSome v when v <> fst plot -> 1
                          | _ -> 0
            ) 0
        |> (fun x -> x + sum)
        )

let movements (plot:Plot) g (visited:HashSet<Point2I>) =
    let plant, point = plot
    movements4 point g
    |> List.choosev (fun px ->
        let vx = get px g |> ifNoneFail "couldn't get point"
        struct(px,vx))
    |> List.filter (fun plotx ->
        let struct(px, vx) = plotx
        vx = plant && not (visited.Contains px))

// visited is needed because I'm using similar logic to the trails, but no stopping point, so I
// need to make sure that it doesn't retrace itself
let rec traverse grid plot (visited:HashSet<Point2I>) =
    let plant, point = plot
    if visited.Contains(point) then []
    else
        visited.Add(point) |> ignore
        let path =
            movements plot grid visited
            |> List.filter (fun struct(newPoint, newPlant) -> newPlant = plant && visited.Contains(newPoint) |> not )
            |> List.map(fun struct(newPoint, newPlant) -> traverse grid (newPlant, newPoint) visited)
            |> List.concat
            |> List.distinct
        plot :: path

/// Returns the list of plots walked and a new grid with the traversed plots set to '.'
let walk (plot:Plot) (farm:Grid<Plant>) : Region * Grid<Plant> =
    let foundMovements = HashSet()
    let region:Region = traverse farm plot foundMovements
    let updatedGrid =
        let arr = Array2D.copy farm
        for _, p in region do
            set p arr '.' |> ignore
        arr
    (region, updatedGrid)
    
let rec findRegions (farm:Grid<Plant>) : Region list=
    farm
    |> List.unfold (fun arr ->
        match (findFirst (fun struct(_,_,v) -> v <> '.' )) arr with
        | Some value ->
            let struct(x,y,v) = value
            let point = {X = x; Y = y}
            let plot : Plot = (v, point)
            let region, newFarm = walk plot arr
            Some (region, newFarm)
        | None -> None
    )
    
let part1 input =
    (readGrid2D input (fun _ c -> c))
    |> fun grid ->
        findRegions grid
        |> List.sumBy (fun region ->
            let a = area region
            let p = perimeter region grid
            a * p)

// Part 2 ---------------------------------------------
[<Flags>]
type Side = None = 0 | Top = 1 | Right = 2| Left = 4 | Bottom = 8
type PlotWithFence = Plot * Side 

type SideAndNextPoint = Side * Point2I

// I couldn't use my original movement function because it filters out off-grid positions, so I modified it here
let getSides plot grid =
    let toPlot (side:Side) (voption:Point2I voption) =
        match voption with | ValueNone -> None, side | ValueSome point -> (Some point, side)
    [
        l (snd plot) |> toPlot Side.Left
        r (snd plot) grid |> toPlot Side.Right
        u (snd plot) |> toPlot Side.Top
        d (snd plot) grid |> toPlot Side.Bottom
    ]


let rec findEdges grid (plot:Plot) (visited:HashSet<Point2I>) =
    
    // this attempt that works is to attach the side information to each point
    // I didn't see a great way to use the existing movements function, so I copied it and added a mapping
    // so that I know in what direction the movement options are
    let sidesWithFence = getSides plot grid

    let plant, point = plot
    if visited.Add(point) |> not then Side.None
    else
        // use the movements to find edges
        let edges = 
            sidesWithFence
            |> List.fold (fun sides next ->
                match next with
                | None, side ->  sides ||| side
                | Some point, side when (get point grid >>= fun v -> v <> plant) |> ifNone false -> sides ||| side
                | _ -> sides
            ) Side.None
            
        edges

let getSideCount2 (plotFences:(Point2I * Side) list) =
    // ok, now I have information on each SIDE that a fence is one... omg I suck at this.
    // I'll try to do the whole compare horizontally and vertically thing again, but this time
    // within each I'll have to check the top and bottom, or I'll iterate it twice
    
    let getX (pf:Point2I * Side) : int = (fst pf) |> _.X
    let getY (pf:Point2I * Side) : int = (fst pf) |> _.Y
    
    let countContiguous side group sort =
        plotFences
        |> Seq.filter (fun pf -> (snd pf) &&& side = side)
        |> Seq.groupBy group 
        |> Seq.map(fun (key, g) -> g |> Seq.sortBy sort)
        // |> Array.ofSeq // debugging code
        |> Seq.sumBy(fun grouping ->
            let total =
                grouping
                |> Seq.splitByComparison (fun last current -> 
// splitByComparison is an implementation I took from ChatGPT for a function that I commonly use in C# as part of the MoreLinq library that does the same thing. Here, I'm splitting whenever there is a difference. 
// in hindsight, it probably could have been a window
                    let l = sort last 
                    let r = sort current
                    l <> (r - 1)
                )
                |> Seq.length
            total)
    
    let topCounts = countContiguous Side.Top getY getX
    let bottomCounts = countContiguous Side.Bottom getY getX
    let leftCounts = countContiguous Side.Left getX getY
    let rightCounts = countContiguous Side.Right getX getY
    
    topCounts + bottomCounts + leftCounts + rightCounts


let part2 input =
    (readGrid2D input (fun _ c -> c))
    |> fun grid ->
        findRegions grid
        // |> List.take 1
        |> List.sumBy(fun region ->
            let (plotCount, edgecount) =
                let visited = HashSet()
                let regionCounts =
                    region
                    |> List.map(fun p -> (snd p), findEdges grid p visited)
                    |> getSideCount2
                (visited.Count, regionCounts)
            
            let area = plotCount
            area * edgecount
            )

[โ€“] [email protected] 8 points 8 months ago (1 children)

Not just any insane men. Live ones!

[โ€“] [email protected] 10 points 8 months ago (1 children)

As one user posted, the best way is to do them manually. Proton has a spam filter, but their whole thing is not reading your email.

[โ€“] [email protected] 3 points 8 months ago (1 children)

I think the background choice is fine, it's not like she has to ditch the tech because she left the city or anything. Just going a stroll, watching for bears.

I like the piece! I never heard of that game though. Sounds fun!

[โ€“] [email protected] 17 points 8 months ago

I love the old guy they quoted: we built tunnels to hide from the Americans, building one for a train shouldn't be hard! ๐Ÿคฃ

Back in my day, we dug them out by hand, had no light, and had to haul the dirt back ourselves! You kids have it too easy!

[โ€“] [email protected] 1 points 8 months ago

I'm way behind, but I'm trying to learn F#.

I'm using the library Combinatorics in dotnet, which I've used in the past, generate in this case every duplicating possibility of the operations. I the only optimization that I did was to use a function to concatenate numbers without converting to strings, but that didn't actually help much.

I have parser helpers that use ReadOnlySpans over strings to prevent unnecessary allocations. However, here I'm adding to a C# mutable list and then converting to an FSharp (linked) list, which this language is more familiar with. Not optimal, but runtime was pretty good.

I'm not terribly good with F#, but I think I did ok for this challenge.

F#

// in another file:
let concatenateLong (a:Int64) (b:Int64) : Int64 =
    let rec countDigits (n:int64) =
        if n = 0 then 0
        else 1 + countDigits (n / (int64 10))   

    let bDigits = if b = 0 then 1 else countDigits b
    let multiplier = pown 10 bDigits |> int64
    a * multiplier + b

// challenge file
type Operation = {Total:Int64; Inputs:Int64 list }

let parse (s:ReadOnlySpan<char>) : Operation =
    let sep = s.IndexOf(':')
    let total = Int64.Parse(s.Slice(0, sep))
    let inputs = System.Collections.Generic.List<Int64>()
    let right:ReadOnlySpan<char> = s.Slice(sep + 1).Trim()

   // because the Split function on a span returns a SpanSplitEnumerator, which is a ref-struct and can only live on the stack, 
   // I can't use the F# list syntax here
    for range in right.Split(" ") do
        inputs.Add(Int64.Parse(sliceRange right range))
        
    {Total = total; Inputs = List.ofSeq(inputs) }

let part1Ops = [(+); (*)]

let execute ops input =
    input
    |> PSeq.choose (fun op ->
        let total = op.Total
        let inputs = op.Inputs
        let variations = Variations(ops, inputs.Length - 1, GenerateOption.WithRepetition)
        variations
        |> Seq.tryFind (fun v ->
            let calcTotal = (inputs[0], inputs[1..], List.ofSeq(v)) |||> List.fold2 (fun acc n f -> f acc n) 
            calcTotal = total
            )
        |> Option.map(fun _ -> total)
        )
    |> PSeq.fold (fun acc n -> acc + n) 0L

let part1 input =
    (read input parse)
    |> execute part1Ops

let part2Ops = [(+); (*); concatenateLong]

let part2 input = (read input parse) |> execute part2Ops

The Gen0 garbage collection looks absurd, but Gen0 is generally considered "free".

Method Mean Error StdDev Gen0 Gen1 Allocated
Part1 19.20 ms 0.372 ms 0.545 ms 17843.7500 156.2500 106.55 MB
Part2 17.94 ms 0.355 ms 0.878 ms 17843.7500 156.2500 106.55 MB

V2 - concatenate numbers did little for the runtime, but did help with Gen1 garbage, but not the overall allocation.

Method Mean Error StdDev Gen0 Gen1 Allocated
Part1 17.34 ms 0.342 ms 0.336 ms 17843.7500 125.0000 106.55 MB
Part2 17.24 ms 0.323 ms 0.270 ms 17843.7500 93.7500 106.55 MB
[โ€“] [email protected] 1 points 8 months ago (1 children)

I'm way behind in AoC this year, but I thought I'd give some feedback. I haven't used gleam, but I'm using F# and this looks quite similar:

let new_pos = case guard.direction {
    North -> #(-1, 0)
    East -> #(0, 1)
    South -> #(1, 0)
    West -> #(0, -1)
  }

I never thought of doing that to change points. thumbs up!

Overall your approach looks good.

[โ€“] [email protected] 4 points 8 months ago

Hol' up a minute

[โ€“] [email protected] 8 points 8 months ago (1 children)

Oh this is actually a real thing I was rolling my eyes like "just show me the clicks and clucks in the code"

[โ€“] [email protected] 4 points 8 months ago

It was managed, just not for his benefit

view more: โ€น prev next โ€บ