8 votes

Day 2: Fulminating Farmland

Today's problem description: https://adventofcode.com/2026/day/2

Please post your solutions in your own top-level comment. Here's a template you can copy-paste into your comment to format it nicely, with the code collapsed by default inside an expandable section with syntax highlighting (you can replace python with any of the "short names" listed in this page of supported languages):

<details>
<summary>Part 1</summary>

```python
Your code here.
```

</details>

10 comments

  1. lily
    (edited )
    Link
    Took some time to clean this up a bit before posting it, though it could probably still stand to be made more succinct. I used the waypoint characters directly when solving this initially, but...

    Took some time to clean this up a bit before posting it, though it could probably still stand to be made more succinct. I used the waypoint characters directly when solving this initially, but that made part 2 especially kind of ugly. Instead, I now convert the waypoints to integers (from 0 to 5), which as a bonus allows part 1 to be done more efficiently. Part 2 is handled by keeping track of how many of each waypoint remain, and repeatedly selecting the most optimal waypoint that's still available.

    Solution (Lily)
    var program: List[Integer] = []
    
    var waypoints: Hash[Integer, Integer] = [
        'r' => 0, 'o' => 1, 'y' => 2, 'g' => 3, 'b' => 4, 'v' => 5
    ]
    
    for char in File.read_to_string("inputs/day_02.txt"): {
        # The `+ 0` coerces `char` to an `Integer` (`Byte`s can't be `Hash` keys).
        program.push(waypoints[char + 0])
    }
    
    var total_distance = 0
    var current_waypoint = 0
    
    var counts = [0, 0, 0, 0, 0, 0]
    
    for waypoint in program: {
        total_distance += (
            waypoint <= current_waypoint ? waypoint + 6 : waypoint
        ) - current_waypoint
    
        current_waypoint = waypoint
        counts[waypoint] += 1
    }
    
    print("Part 1: {}".format(total_distance))
    
    total_distance = 0
    current_waypoint = 0
    
    for _ in 1...program.size(): {
        for distance in 6...1 by -1: {
            var waypoint = current_waypoint - distance
            if waypoint < 0: {
                waypoint += 6
            }
    
            if counts[waypoint] > 0: {
                total_distance += distance
                current_waypoint = waypoint
                counts[waypoint] -= 1
                break
            }
        }
    }
    
    print("Part 2: {}".format(total_distance))
    
    2 votes
  2. [2]
    Boojum
    Link
    This is kind of brute-force and ugly, especially the Part 2 solution. I believe that it could be made a decent bit shorter, but oh well. Namely, I think there's a static ordering that is always...

    This is kind of brute-force and ugly, especially the Part 2 solution. I believe that it could be made a decent bit shorter, but oh well. Namely, I think there's a static ordering that is always optimal.

    Part 1
    import itertools
    print( sum( "roygbvroygbv".index( b, ( s := "roygbv".index( a ) ) + 1 ) - s
                for a, b in itertools.pairwise( "r" + open( 0 ).read().strip() ) ) )
    
    Part 2
    import collections, itertools
    f = collections.Counter( open( 0 ).read().strip() )
    print( max( sum( "roygbvroygbv".index( b, ( s := "roygbv".index( a ) ) + 1 ) - s
                     for a, b in itertools.pairwise( "r" + "".join( i * f[ i ] for i in p ) ) )
                for p in itertools.permutations( f.keys() ) ) )
    

    Visualization

    2 votes
    1. thecakeisalime
      Link Parent
      For part 2, you're correct that there's a static order. When the colour is the same, the step size is always 6, so you only need to maximize the step size when the colour changes. So if you can...

      For part 2, you're correct that there's a static order. When the colour is the same, the step size is always 6, so you only need to maximize the step size when the colour changes. So if you can find the optimal ordering of 'roygbv', you've found the optimal ordering of the sorted list.

      EDIT: I looked at your Reddit post and it seems like you've already figured this out.

  3. tomf
    (edited )
    Link
    This could be way cleaner... the second part was a waste of time. Not that these should be way harder, but three of four have been trivial. Google Sheets ={MAX( IFERROR( SCAN( 0, INDEX( MOD(...

    This could be way cleaner... the second part was a waste of time. Not that these should be way harder, but three of four have been trivial.

    Google Sheets
     ={MAX(
       IFERROR(
        SCAN(
         0,
         INDEX(
          MOD(
           FIND(MID(A1,SEQUENCE(LEN(A1)),1),"roygbv",1)-
           FIND({"r";MID(A1,SEQUENCE(LEN(A1)-1),1)},"roygbv",1)-1,6)+1),
         LAMBDA(a,b,a+b))));
       6*len(A1)-5}
    
    1 vote
  4. vsczpv
    Link
    When I started doing Part 2 for a moment I thought I was getting to reuse Day 01's code, but the ordering of instructions always been the same saved me from abusing BTreeMap a second time. Both...

    When I started doing Part 2 for a moment I thought I was getting to reuse Day 01's code, but the ordering of instructions always been the same saved me from abusing BTreeMap a second time.

    Both Parts (Rust)
    fn color_to_index(color: char) -> i32 {
        match color {
            'r' => 0,
            'o' => 1,
            'y' => 2,
            'g' => 3,
            'b' => 4,
            'v' => 5,
            _ => panic!("no number {}", color as u32),
        }
    }
    
    fn count_steps(input: String) -> i32 {
        let mut sequence = 0;
        for ins in input.chars() {
            if !(ins >= 'a' && ins <= 'z') {
                continue;
            }
            let goto = color_to_index(ins);
            sequence += 1;
            while (sequence % 6) != goto {
                sequence += 1;
            }
        }
        sequence
    }
    
    fn rearrange(input: String) -> String {
        let mut hist = HashMap::new();
    
        for c in input.chars() {
            hist.entry(c).and_modify(|e| *e += 1).or_insert(1usize);
        }
    
        let res =
              "r".repeat(*hist.get(&'r').unwrap_or(&0usize))
            + "v".repeat(*hist.get(&'v').unwrap_or(&0usize)).as_str()
            + "b".repeat(*hist.get(&'b').unwrap_or(&0usize)).as_str()
            + "g".repeat(*hist.get(&'g').unwrap_or(&0usize)).as_str()
            + "y".repeat(*hist.get(&'y').unwrap_or(&0usize)).as_str()
            + "o".repeat(*hist.get(&'o').unwrap_or(&0usize)).as_str();
    
        res
    }
    
    pub fn main(part: Part) {
        let file = std::fs::read_to_string(PATH).expect(format!("Error: {} missing!", PATH).as_str());
    
        match part {
            Part::One => println!("{}", count_steps(file)),
            Part::Two => println!("{}", count_steps(rearrange(file.clone()))),
        }
    }
    
  5. FlappyFish
    Link
    For part 2, I spotted that you just need the length of the string and which colours occur in order to calculate the furthest distance, but I couldn't figure out how to cleanly count the jumps for...

    For part 2, I spotted that you just need the length of the string and which colours occur in order to calculate the furthest distance, but I couldn't figure out how to cleanly count the jumps for the occurring colours in one line without using my previous algorithm. I didn't consider that I could just assume that all the colours occur, due to the length of the string

    Part 1
    print(sum([((- prev + (prev := 'roygbv'.index(char) + 1) - 1) % 6) + 1 if 'prev' in locals() else (prev := 1) for char in " " + open("input.txt").read(-1)]) - 1)
    
    Part 2
    print(sum([((- prev + (prev := 'roygbv'.index(char) + 1) - 1) % 6) + 1 if 'prev' in locals() else (prev := 1) for char in " " + ''.join([(char * open("input.txt").read(-1).count(char)) for char in "rvbgyo"])]) - 1)
    
  6. kari
    (edited )
    Link
    Both parts in Gleam! Part 1 It doesn't feel super idiomatic maybe? I dunno, functional programming is fun but I think I don't do it enough so I always make unreadable code lol. const ring_size = 6...

    I'm still working on part 2 but figured I'd share my part 1:

    Both parts in Gleam!

    Part 1

    It doesn't feel super idiomatic maybe? I dunno, functional programming is fun but I think I don't do it enough so I always make unreadable code lol.

    const ring_size = 6
    
    /// Given a color in ROYGBV, return its position in the waypoitn loop.
    fn waypoint(color: String) -> Result(Int, Nil) {
      case color {
        "r" -> Ok(0)
        "o" -> Ok(1)
        "y" -> Ok(2)
        "g" -> Ok(3)
        "b" -> Ok(4)
        "v" -> Ok(5)
        // Shouldn't really hit this
        _ -> Error(Nil)
      }
    }
    
    type Status {
      Status(current_position: Int, total_distance_moved: Int)
    }
    
    fn input_to_program(input: String) -> Result(List(Int), Nil) {
      string.split(input, on: "")
      |> list.filter(fn(wp) {
        wp |> string.trim() |> string.is_empty() |> bool.negate()
      })
      |> list.try_map(waypoint)
    }
    
    /// Part 1?
    pub fn part1(input: String) -> Int {
      // Convert the input into a program of waypoints
      // Now that we have the program, calculate our steps through
      let assert Ok(program) =
        input
        |> input_to_program()
    
      program
      |> list.fold(Status(0, 0), fn(acc, next_wp) {
        // We just fold with an accumulator keeping our current_pos and total_pos as we go through
        Status(
          current_position: next_wp,
          total_distance_moved: acc.total_distance_moved
            + case int.compare(next_wp, acc.current_position) {
            order.Lt | order.Eq -> ring_size - acc.current_position + next_wp
            order.Gt -> next_wp - acc.current_position
          },
        )
      })
      |> fn(status) { status.total_distance_moved }
    }
    
    Part 2

    consume_sorted() is actually a noop right now because I got kinda stuck with looping in gleam :P butttt I realized if I just get the counts of the waypoints it's trivial to do the rest.

    e.g. [#(0, 2), #(2, 2), #(4, 2)] from one of the examples (where 0 is "r", 1 is "o", etc. and the second value is the count of that waypoint in the program), we can do 26 because we start at r so that's the longest, then the next longest is to 4 so 26+4 and we've got [#(2, 2), #(4, 1] left, so 26+4+16 then repeat for the 2 26+4+16+4+1*6. Works the same for the large input so I just did that in a calculator and got the answer. I still can't wrap my head around how to implement the algorithm without loops! Not used to this stuff.

    pub fn part2(input: String) -> Int {
      let assert Ok(program) =
        input
        |> input_to_program()
    
      // We want a count of each letter in the program
      // sorted
      let counts =
        program
        |> list.fold(dict.new(), fn(acc, next_wp) {
          let count = case dict.get(acc, next_wp) {
            Ok(n) -> n + 1
            _ -> 1
          }
    
          dict.insert(acc, next_wp, count)
        })
        |> dict.to_list()
        |> list.sort(fn(a, b) { int.compare(a.0, b.0) })
        |> echo
    
      counts |> consume_sorted(Status(0, 0))
    }
    

    I actually didn't even finish my program for part 2 because I'm so bad at gleam but I figured out it's pretty easy to get the answer (more in the details).

  7. fidwell
    (edited )
    Link
    Not a terribly "clean" solution; just a do-what-the-problem-says approach. It does turn out you can greedily optimize part 2 and it works just fine, to reduce 991 loops down to 5, but I'm not sure...

    Not a terribly "clean" solution; just a do-what-the-problem-says approach. It does turn out you can greedily optimize part 2 and it works just fine, to reduce 991 loops down to 5, but I'm not sure if that would hold generally. (I think I saw someone say that would be NP-hard, so it probably wouldn't be appropriate for day 2.)

    Part 1
    public override object SolvePartOne(string input)
    {
        var current = 0; // roygbv index 0, or 'r'
        var total = 0;
    
        foreach (var waypoint in input.Trim().ToCharArray())
        {
            var target = ToWaypointIndex(waypoint);
    
            if (target <= current)
            {
                current -= 6;
            }
            var diff = target - current;
            total += diff;
            current = target;
        }
    }
    
    private static int ToWaypointIndex(char w) => w switch
    {
        'r' => 0,
        'o' => 1,
        'y' => 2,
        'g' => 3,
        'b' => 4,
        'v' => 5,
        _ => throw new NotSupportedException(),
    };
    
    Part 2
    public override object SolvePartTwo(string input)
    {
        var dict = input.Trim()
            .ToCharArray()
            .Select(ToWaypointIndex)
            .GroupBy(w => w)
            .ToDictionary(w => w.Key, w => w.Count());
        var current = 0; // roygbv index 0, or 'r'
        var total = 0;
    
        // Greedy algorithm. Assume it's optimal to always take the farthest waypoint.
        while (dict.Count != 0)
        {
            var distances = dict.Select(w => (Key: w, Distance: DistanceTo(current, w.Key)));
            var max = distances.Max(d => d.Distance);
            var nextWaypoint = distances.First(d => d.Distance == max).Key.Key;
    
            // One "max" to get us there, then n-1 loops of length 6.
            var loopCount = dict[nextWaypoint] - 1;
            total += max + loopCount * 6;
            current = nextWaypoint;
            dict.Remove(nextWaypoint);
        }
    
        return total;
    }
    
    private static int DistanceTo(int from, int to) =>
        from < to
            ? to - from
            : to - from + 6;
    
  8. Kremor
    Link
    Here's my solution in Guile Day 2: Fulminating Farmland (use-modules (ice-9 rdelim) (srfi srfi-1) ; take drop (srfi srfi-11)) ; let-values ;; Read input (define (read-file path)...

    Here's my solution in Guile

    Day 2: Fulminating Farmland
    (use-modules (ice-9 rdelim)
                 (srfi srfi-1)   ; take drop
                 (srfi srfi-11)) ; let-values
    
    ;; Read input
    
    (define (read-file path)
        (call-with-input-file path
            (lambda (port)
                (string-trim-right (read-line port)))))
    
    ;; Part 1
    
    (define (to-val c)
        (case c
            ((#\r) 0)
            ((#\o) 1)
            ((#\y) 2)
            ((#\g) 3)
            ((#\b) 4)
            (else 5)))
    
    (define (ab-dist a b)
        (if (< a b)
            (- b a)
            (+ 6 (- b a))))
    
    
    (define (calc-dist items)
        (let loop ((remaining items)
                   (prev 0)
                   (acc '()))
            (if (null? remaining)
                (reverse acc)
                (loop (cdr remaining)
                      (car remaining)
                      (cons (ab-dist prev (car remaining))
                            acc)))))
    
    ;; Part 2
    
    (define (get-max-idx lst)
        (let loop ((items lst)
                   (idx 0)
                   (best 0)
                   (maxv 0))
            (if (null? items)
                (values best maxv)
                (let ((x (car items)))
                    (cond
                        ((= x 6)    (values idx x))
                        ((> x maxv) (loop (cdr items) (1+ idx) idx x))
                        (else       (loop (cdr items) (1+ idx) best maxv)))))))
    
    (define (remove-idx lst idx)
      (append (take lst idx)
              (drop lst (1+ idx))))
    
    (define (calc-dist-part2 pos items)
      (map (lambda (item) (ab-dist pos item)) items))
    
    (define (longest-dist items)
      (let loop ((remaining items)
                 (curr 0)
                 (acc 0))
        (if (null? remaining)
            acc
            (let ((dists (map (lambda (x) (ab-dist curr x)) remaining)))
              (let-values (((idx max-dist) (get-max-idx dists)))
                (loop (remove-idx remaining idx)
                      (list-ref remaining idx)
                      (+ acc max-dist)))))))
    
    ;; Results
    
    (define input (map to-val (string->list (read-file "input.txt"))))
    
    (format #t "Part 1: ~a~%" (apply + (calc-dist input)))
    (format #t "Part 2: ~a~%" (longest-dist input))
    
  9. Banazir
    Link
    Solutions for both parts in Lua: Both parts local pattern = "roygbv" local distance = 0 local lastpos = nil local curpos = 1 local colorcounts = { ['r'] = 0, ['o'] = 0, ['y'] = 0, ['g'] = 0, ['b']...

    Solutions for both parts in Lua:

    Both parts
    local pattern = "roygbv"
    
    local distance = 0
    local lastpos = nil
    local curpos = 1
    
    local colorcounts = {
    	['r'] = 0,
    	['o'] = 0,
    	['y'] = 0,
    	['g'] = 0,
    	['b'] = 0,
    	['v'] = 0,
    }
    
    local infile = io.open("input", "r")
    local route = infile:read("a")
    infile:close()
    
    for i = 1,#route do
    	local step = string.sub(route, i, i)
    	if not string.match(step, "%l") then break end -- make sure it's a usable character and not \n or \0 at the end of the file or line
    	colorcounts[step] = colorcounts[step] + 1
    	lastpos = curpos
    	curpos = string.find(pattern, step, 1)
    	local move = (function(x, y) 
    		local val = y - x
    		if val <= 0 then return val + 6 else return val end
    	end)(lastpos, curpos)
    	distance = distance + move
    end
    
    print(distance) -- part 1 solution
    
    local maxdistance = 0
    local maxpattern = "rvbgyo"
    local maxroute = ""
    
    for i=1,#maxpattern do
    	local step = string.sub(maxpattern,i,i)
    	maxroute = maxroute .. string.rep(step,colorcounts[step])
    end
    
    lastpos = nil
    curpos = 1
    
    for i = 1,#maxroute do
    	local step = string.sub(maxroute, i, i)
    	lastpos = curpos
    	curpos = string.find(pattern, step, 1)
    	local move = (function(x, y) 
    		local val = y - x
    		if val <= 0 then return val + 6 else return val end
    	end)(lastpos, curpos)
    	maxdistance = maxdistance + move
    end
    
    print(maxdistance) -- part 2 solution