Day 18: Ram Run

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)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • @SteveDinn@lemmy.ca
    link
    fedilink
    11 hour ago

    C#

    Part 1 was straight forward Dykstra with a cost of 1 for each move. Part 2 was a binary search from the number of corrupted bytes given to us for Part 1 (where we know a path can be found) to the total number of corrupted bytes.

    using System.Collections.Immutable;
    using System.Diagnostics;
    using Common;
    
    namespace Day18;
    
    static class Program
    {
        static void Main()
        {
            var start = Stopwatch.GetTimestamp();
    
            var sampleInput = ReceiveInput("sample.txt");
            var sampleBounds = new Point(7,7);
            
            var programInput = ReceiveInput("input.txt");
            var programBounds = new Point(71, 71);
    
            Console.WriteLine($"Part 1 sample: {Part1(sampleInput, 12, sampleBounds)}");
            Console.WriteLine($"Part 1 input: {Part1(programInput, 1024, programBounds)}");
    
            Console.WriteLine($"Part 2 sample: {Part2(sampleInput, 12, sampleBounds)}");
            Console.WriteLine($"Part 2 input: {Part2(programInput, 1024, programBounds)}");
    
            Console.WriteLine($"That took about {Stopwatch.GetElapsedTime(start)}");
        }
    
        static int Part1(ImmutableArray<Point> input, int num, Point bounds) => FindBestPath(
            new Point(0, 0),
            new Point(bounds.Row - 1, bounds.Col - 1),
            input.Take(num).ToImmutableHashSet(),
            bounds);
    
        static object Part2(ImmutableArray<Point> input, int num, Point bounds)
        {
            var start = num;
            var end = input.Length;
            
            while (start != end)
            {
                var check = (start + end) / 2;
                if (Part1(input, check, bounds) < 0) end = check;
                else start = check + 1;
            }
    
            var lastPoint = input[start - 1];
            return $"{lastPoint.Col},{lastPoint.Row}";
        }
    
        record struct State(Point Location, int Steps);
    
        static int FindBestPath(Point start, Point end, ISet<Point> corruptedBytes, Point bounds)
        {
            var seenStates = new Dictionary<Point, int>();
    
            var queue = new Queue<State>();
            queue.Enqueue(new State(start, 0));
            while (queue.TryDequeue(out var state))
            {
                if (state.Location == end) return state.Steps;
                
                if (seenStates.TryGetValue(state.Location, out var bestSteps))
                {
                    if (state.Steps >= bestSteps) continue;
                }
                
                seenStates[state.Location] = state.Steps;
                queue.EnqueueRange(state.Location.GetCardinalMoves()
                    .Where(p => p.IsInBounds(bounds) && !corruptedBytes.Contains(p))
                    .Select(p => new State(p, state.Steps + 1)));
            }
    
            return -1;
        }
    
        static ImmutableArray<Point> ReceiveInput(string file) => File.ReadAllLines(file)
            .Select(l => l.Split(','))
            .Select(p => new Point(int.Parse(p[1]), int.Parse(p[0])))
            .ToImmutableArray();
    }
    
  • @Gobbel2000@programming.dev
    link
    fedilink
    12 hours ago

    Rust

    Naive approach running BFS after every dropped byte after 1024. Still runs in 50ms. This could be much optimized by using binary search to find the first blocked round and using A* instead of BFS, but I didn’t feel like doing more today.

    Solution
    use std::collections::VecDeque;
    
    use euclid::{default::*, vec2};
    
    fn parse(input: &str) -> Vec<Point2D<i32>> {
        input
            .lines()
            .map(|l| {
                let (x, y) = l.split_once(',').unwrap();
                Point2D::new(x.parse().unwrap(), y.parse().unwrap())
            })
            .collect()
    }
    
    const BOUNDS: Rect<i32> = Rect::new(Point2D::new(0, 0), Size2D::new(71, 71));
    const START: Point2D<i32> = Point2D::new(0, 0);
    const TARGET: Point2D<i32> = Point2D::new(70, 70);
    const N_BYTES: usize = 1024;
    const DIRS: [Vector2D<i32>; 4] = [vec2(1, 0), vec2(0, 1), vec2(-1, 0), vec2(0, -1)];
    
    fn adj(
        field: &[[bool; BOUNDS.size.width as usize]],
        v: Point2D<i32>,
    ) -> impl Iterator<Item = Point2D<i32>> + use<'_> {
        DIRS.iter()
            .map(move |&d| v + d)
            .filter(|&next| BOUNDS.contains(next) && !field[next.y as usize][next.x as usize])
    }
    
    fn find_path(field: &[[bool; BOUNDS.size.width as usize]]) -> Option<u32> {
        let mut seen = [[false; BOUNDS.size.width as usize]; BOUNDS.size.height as usize];
        let mut q = VecDeque::from([(START, 0)]);
        seen[START.y as usize][START.x as usize] = true;
        while let Some((v, dist)) = q.pop_front() {
            for w in adj(field, v) {
                if w == TARGET {
                    return Some(dist + 1);
                }
                if !seen[w.y as usize][w.x as usize] {
                    seen[w.y as usize][w.x as usize] = true;
                    q.push_back((w, dist + 1));
                }
            }
        }
        None
    }
    
    fn part1(input: String) {
        let bytes = parse(&input);
        let mut field = [[false; BOUNDS.size.width as usize]; BOUNDS.size.height as usize];
        for b in &bytes[..N_BYTES] {
            field[b.y as usize][b.x as usize] = true;
        }
        println!("{}", find_path(&field).unwrap());
    }
    
    fn part2(input: String) {
        let bytes = parse(&input);
        let mut field = [[false; BOUNDS.size.width as usize]; BOUNDS.size.height as usize];
        for (i, b) in bytes.iter().enumerate() {
            field[b.y as usize][b.x as usize] = true;
            // We already know from part 1 that below N_BYTES there is a path
            if i > N_BYTES && find_path(&field).is_none() {
                println!("{},{}", b.x, b.y);
                break;
            }
        }
    }
    
    util::aoc_main!();
    

    Also on github

  • @mykl@lemmy.world
    link
    fedilink
    2
    edit-2
    4 hours ago

    Dart

    I knew keeping my search code from day 16 would come in handy, I just didn’t expect it to be so soon.

    For Part 2 it finds that same path (laziness on my part), then does a simple binary chop to home in on the last valid path. (was then searches for the first block that will erm block that path, and re-runs the search after that block has dropped, repeating until blocked. Simple but okay. )

    90 lines, half of which is my copied search method. Runs in a couple of seconds which isn’t great, but isn’t bad. Binary chop dropped it to 200ms.

    import 'dart:math';
    import 'package:collection/collection.dart';
    import 'package:more/more.dart';
    
    var d4 = <Point<num>>[Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0)];
    
    solve(List<String> lines, int count, Point end, bool inPart1) {
      var blocks = (lines
          .map((e) => e.split(',').map(int.parse).toList())
          .map((p) => Point<num>(p[0], p[1]))).toList();
      var blocksSofar = blocks.take(count).toSet();
      var start = Point(0, 0);
      Map<Point, num> fNext(Point here) => {
            for (var d in d4
                .map((d) => d + here)
                .where((e) =>
                    e.x.between(start.x, end.x) &&
                    e.y.between(start.y, end.y) &&
                    !blocksSofar.contains(e))
                .toList())
              d: 1
          };
    
      int fHeur(Point here) => 1;
      bool fAtEnd(Point here) => here == end;
      var cost = aStarSearch<Point>(start, fNext, fHeur, fAtEnd);
    
      if (inPart1) return cost.first;
      var lo = count, hi = blocks.length;
      while (lo <= hi) {
        var mid = (lo + hi) ~/ 2;
        blocksSofar = blocks.take(mid).toSet();
        cost = aStarSearch<Point>(start, fNext, fHeur, fAtEnd);
        (cost.first > 0) ? lo = mid + 1 : hi = mid - 1;
      }
      var p = blocks[lo - 1];
      return '${p.x},${p.y}';
    }
    
    part1(lines, count, end) => solve(lines, count, end, true);
    part2(lines, count, end) => solve(lines, count, end, false);
    
    That search method
    /// Returns cost to destination, plus list of routes to destination.
    /// Does Dijkstra/A* search depending on whether heuristic returns 1 or
    /// something better.
    (num, List<List<T>>) aStarSearch<T>(T start, Map<T, num> Function(T) fNext,
        int Function(T) fHeur, bool Function(T) fAtEnd,
        {multiplePaths = false}) {
      var cameFrom = SetMultimap<T, T>.fromEntries([MapEntry(start, start)]);
    
      var ends = <T>{};
      var front = PriorityQueue<T>((a, b) => fHeur(a).compareTo(fHeur(b)))
        ..add(start);
      var cost = <T, num>{start: 0};
      while (front.isNotEmpty) {
        var here = front.removeFirst();
        if (fAtEnd(here)) {
          ends.add(here);
          continue;
        }
        var ns = fNext(here);
        for (var n in ns.keys) {
          var nCost = cost[here]! + ns[n]!;
          if (!cost.containsKey(n) || nCost < cost[n]!) {
            cost[n] = nCost;
            front.add(n);
            cameFrom.removeAll(n);
            cameFrom[n].add(here);
          }
          if (multiplePaths && cost[n] == nCost) cameFrom[n].add(here);
        }
      }
    
      Iterable<List<T>> routes(T h) sync* {
        if (h == start) {
          yield [h];
          return;
        }
        for (var p in cameFrom[h]) {
          yield* routes(p).map((e) => e + [h]);
        }
      }
    
      if (ends.isEmpty) return (-1, []);
      var minCost = ends.map((e) => cost[e]!).min;
      ends = ends.where((e) => cost[e]! == minCost).toSet();
      return (minCost, ends.fold([], (s, t) => s..addAll(routes(t).toList())));
    }
    
  • lwhjp
    link
    18 hours ago

    Haskell

    I did an easy optimization for part 2, but it’s not too slow without.

    Solution
    import Control.Monad
    import Data.Ix
    import Data.List
    import Data.Map qualified as Map
    import Data.Maybe
    import Data.Set (Set)
    import Data.Set qualified as Set
    
    readInput :: String -> [(Int, Int)]
    readInput = map readCoords . lines
      where
        readCoords l = let (a, _ : b) = break (== ',') l in (read a, read b)
    
    findRoute :: (Int, Int) -> Set (Int, Int) -> Maybe [(Int, Int)]
    findRoute goal blocked = go Set.empty (Map.singleton (0, 0) [])
      where
        go seen paths
          | Map.null paths = Nothing
          | otherwise =
              (paths Map.!? goal)
                `mplus` let seen' = Set.union seen (Map.keysSet paths)
                            paths' =
                              (`Map.withoutKeys` seen')
                                . foldl' (flip $ uncurry Map.insert) Map.empty
                                . concatMap (\(p, path) -> (,p : path) <$> step p)
                                $ Map.assocs paths
                         in go seen' paths'
        step (x, y) = do
          (dx, dy) <- [(0, -1), (0, 1), (-1, 0), (1, 0)]
          let p' = (x + dx, y + dy)
          guard $ inRange ((0, 0), goal) p'
          guard $ p' `Set.notMember` blocked
          return p'
    
    dropAndFindRoutes goal skip bytes =
      let drops = drop skip $ zip bytes $ drop 1 $ scanl' (flip Set.insert) Set.empty bytes
       in zip (map fst drops) $ scanl' go (findRoute goal (snd $ head drops)) $ tail drops
      where
        go route (p, blocked) = do
          r <- route
          if p `elem` r then findRoute goal blocked else route
    
    main = do
      input <- readInput <$> readFile "input18"
      let routes = dropAndFindRoutes (70, 70) 1024 input
      print $ length <$> (snd . head) routes
      print $ fst <$> find (isNothing . snd) routes
    
  • @VegOwOtenks@lemmy.world
    link
    fedilink
    English
    2
    edit-2
    8 hours ago

    Haskell

    Wasn’t there a pathfinding problem just recently?

    Edit: Optimization to avoid recalculating paths all the time

    Haskell with lambdas
    import Control.Arrow
    import Control.Monad
    import Data.Bifunctor hiding (first, second)
    
    import Data.Set (Set)
    import Data.Map (Map)
    
    import qualified Data.List as List
    import qualified Data.Set as Set
    import qualified Data.Map as Map
    import qualified Data.Maybe as Maybe
    
    parse :: String -> [(Int, Int)]
    parse = map (join bimap read) . map (break (== ',') >>> second (drop 1)) . filter (/= "") . lines
    
    lowerBounds = (0, 0)
    exitPosition = (70, 70)
    initialBytes = 1024
    
    adjacent (py, px) = Set.fromDistinctAscList [(py-1, px), (py, px-1), (py, px+1), (py+1, px)]
    
    data Cost = Wall | Explored Int
            deriving (Show, Eq)
    
    inBounds (py, px)
            | py < 0 = False
            | px < 0 = False
            | py > fst exitPosition = False
            | px > snd exitPosition = False
            | otherwise = True
    
    dijkstra :: Map Int (Set (Int, Int)) -> Map (Int, Int) Cost -> (Int, (Int, Int), Map (Int, Int) Cost)
    dijkstra queue walls
            | Map.null queue = (-1, (-1, -1), Map.empty)
            | minPos == exitPosition = (minKey, minPos, walls)
            | Maybe.isJust (walls Map.!? minPos) = dijkstra remainingQueue' walls
            | not . inBounds $ minPos = dijkstra remainingQueue' walls
            | otherwise = dijkstra neighborQueue updatedWalls
            where
                    ((minKey, posSet), remainingQueue) = Maybe.fromJust . Map.minViewWithKey $ queue
                    (minPos, remainingPosSet) = Maybe.fromJust . Set.minView $ posSet
                    remainingQueue' = if not . Set.null $ remainingPosSet then Map.insert minKey remainingPosSet remainingQueue else remainingQueue
                    neighborQueue = List.foldl (\ m n -> Map.insertWith (Set.union) neighborKey (Set.singleton n) m) remainingQueue' neighbors
                    updatedWalls = Map.insert minPos (Explored minKey) walls
                    neighborKey = minKey + 1
                    neighbors = adjacent minPos
    
    isExplored :: Cost -> Bool
    isExplored Wall = False
    isExplored (Explored _) = True
    
    findPath :: Int -> (Int, Int) -> Map (Int, Int) Cost -> [(Int, Int)]
    findPath n p ts
            | p == lowerBounds = [lowerBounds]
            | n == 0 = error "Out of steps when tracing backwards"
            | List.null neighbors = error "No matching neighbors when tracing backwards"
            | otherwise = p : findPath (pred n) (fst . head $ neighbors) ts
            where
                    neighbors = List.filter ((== Explored (pred n)) . snd) . List.filter (isExplored . snd) . List.map (join (,) >>> second (ts Map.!)) . List.filter inBounds . Set.toList . adjacent $ p
    
    runDijkstra = flip zip (repeat Wall)
            >>> Map.fromList
            >>> dijkstra (Map.singleton 0 (Set.singleton lowerBounds))
    
    fst3 :: (a, b, c) -> a
    fst3 (a, _, _) = a
    
    thrd :: (a, b, c) -> c
    thrd (_, _, c) = c
    
    part1 = take initialBytes
            >>> runDijkstra
            >>> \ (n, _, _) -> n
    
    firstFailing :: [(Int, Int)] -> [[(Int, Int)]] -> (Int, Int)
    firstFailing path (bs:bss)
            | List.last bs `List.notElem` path = firstFailing path bss
            | c == (-1) = List.last bs
            | otherwise = firstFailing (findPath c p ts) bss
            where
                    (c, p, ts) = runDijkstra bs
    
    part2 bs = repeat
            >>> zip [initialBytes..length bs]
            >>> map (uncurry take)
            >>> firstFailing path
            $ bs
            where
                    (n, p, ts) = runDijkstra . take 1024 $ bs
                    path = findPath n p ts
    
    main = getContents
            >>= print
            . (part1 &&& part2)
            . parse
    
  • @hades@lemm.ee
    link
    fedilink
    211 hours ago

    C#

    using QuickGraph;
    using QuickGraph.Algorithms.ShortestPath;
    
    namespace aoc24;
    
    public class Day18 : Solver {
      private int width = 71, height = 71, bytes = 1024;
      private HashSet<(int, int)> fallen_bytes;
      private List<(int, int)> fallen_bytes_in_order;
      private record class Edge((int, int) Source, (int, int) Target) : IEdge<(int, int)>;
      private DelegateVertexAndEdgeListGraph<(int, int), Edge> MakeGraph() => new(GetAllVertices(), GetOutEdges);
    
      private readonly (int, int)[] directions = [(-1, 0), (0, 1), (1, 0), (0, -1)];
    
      private bool GetOutEdges((int, int) arg, out IEnumerable<Edge> result_enumerable) {
        List<Edge> result = [];
        foreach (var (dx, dy) in directions) {
          var (nx, ny) = (arg.Item1 + dx, arg.Item2 + dy);
          if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
          if (fallen_bytes.Contains((nx, ny))) continue;
          result.Add(new(arg, (nx, ny)));
        }
        result_enumerable = result;
        return true;
      }
    
      private IEnumerable<(int, int)> GetAllVertices() {
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            yield return (i, j);
          }
        }
      }
    
      public void Presolve(string input) {
        fallen_bytes_in_order = [..input.Trim().Split("\n")
          .Select(line => line.Split(","))
          .Select(pair => (int.Parse(pair[0]), int.Parse(pair[1])))];
        fallen_bytes = [.. fallen_bytes_in_order.Take(bytes)];
      }
    
      private double Solve() {
        var graph = MakeGraph();
        var search = new AStarShortestPathAlgorithm<(int, int), Edge>(graph, _ => 1, vtx => vtx.Item1 + vtx.Item2);
        search.SetRootVertex((0, 0));
        search.ExamineVertex += vertex => {
          if (vertex.Item1 == width - 1 && vertex.Item2 == width - 1) search.Abort();
        };
        search.Compute();
        return search.Distances[(width - 1, height - 1)];
      }
    
      public string SolveFirst() => Solve().ToString();
    
      public string SolveSecond() {
        foreach (var b in fallen_bytes_in_order[bytes..]) {
          fallen_bytes.Add(b);
          if (Solve() > width*height) return $"{b.Item1},{b.Item2}";
        }
        throw new Exception("solution not found");
      }
    }