Day 2: Fulminating Farmland

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

  • Chais@sh.itjust.works
    link
    fedilink
    arrow-up
    1
    ·
    1 hour ago

    Python

    from pathlib import Path
    
    
    def robot_walk(program: str) -> int:
        w = "roygbv"
        s = 0
        for n in program:
            s += j - I if (j := w.index(n)) > (i := s % 6) else 6 - I + j
        return s
    
    
    def part_one(program: str) -> int:
        return walk_robot(program)
    
    
    def part_two(program: str) -> int:
        return walk_robot("".join(sorted(program, reverse=True, key=lambda c: "oygbvr".index(c))))
    
    
    if __name__ == "__main__":
        input = Path("input").read_text("utf-8")
        print(part_one(input))
        print(part_two(input))
    
  • VegOwOtenks@lemmy.world
    link
    fedilink
    English
    arrow-up
    2
    ·
    4 hours ago

    Haskell

    import Data.List (findIndex, sort)
    import Data.Maybe (mapMaybe)
    import Control.Arrow ((&&&))
    
    data Color = R | O | Y | G | B | V
      deriving (Show, Read, Enum, Eq, Ord)
    fromChar c = toEnum <$> findIndex (==c) "roygbv"
    
    part1 :: [Color] -> Int
    part1 = foldl' go 0
     where
      go pos c
       | current < next = pos + next - current
       | otherwise = pos + (6 - current) + next
       where
        current = pos `mod` 6
        next = fromEnum c
    
    part2 = part1 . reverse . sort
    
    main = print . (part1 &&& part2) . mapMaybe fromChar =<< getContents
    

    Somehow, I’m off by one. I forgot why that was and simply added one before entering my solution.

  • Deebster@programming.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    10 hours ago

    nu

    I got a bit into the weeds with how nushell handled a few things, so this wasn’t the fastest option. Still, I’ve learnt something - surely that makes it worthwhile(…?)

    Part 1 uses modulo 6 (treating r as 6), and p2 is just sorting the waypoints (again with r as 6).

    use std/util repeat
    
    def parse [input] {
      $input | split chars | each {
        match $in {
          'r' => 0,
          'o' => 1,
          'y' => 2,
          'g' => 3,
          'b' => 4,
          'v' => 5,
          _ => { error make "bad input" }
        }
      }
    }
    
    def dist [] {
      mut dist = 0;
      mut location = 0;
      for point in (parse $in) {
        let d = ($point - $location) mod 6
        $dist += if $d > 0 { $d } else { 6 }
        $location = $point
      }
      $dist
    }
    
    def sortpoints [] {
      # make a record/dictionary { point => frequency }
      let freq = $in | split chars | histogram | select value count | transpose -rd
      'rvbgyo' | split chars | reduce --fold "" {|point, out| 
        let n = $freq | get -o $point | default 0
        $out ++ ($point | repeat $n | str join)
      }
    }
    

    $in is for values from the pipeline, so I run p2 as

    ❯ "rybryb" | sortpoints | dist
    32
    
  • Amy@piefed.blahaj.zone
    link
    fedilink
    English
    arrow-up
    3
    ·
    14 hours ago

    Haskell

    Part 2 could be more efficient by grouping and multiplying by 6, but eh…

    import Data.List  
    import Data.Maybe  
    import Data.Ord  
    
    main = do  
      input :: [Int] <-  
        map ((+ 1) . fromJust . (`elemIndex` "oygbvr"))  
          . (head . lines)  
          <$> readFile "input02"  
      let step a b = 6 - ((a - b) `mod` 6)  
          go = print . sum . (zipWith step <*> tail) . (6 :) . ($ input)  
      go id  
      go (sortOn Down)  
    
    • Deebster@programming.dev
      link
      fedilink
      arrow-up
      2
      ·
      8 hours ago

      Of course - reverse the order of the comparison and subtract from 6. I knew there was a mathematical way of avoiding the if zero branch, but I didn’t find it.

      • Amy@piefed.blahaj.zone
        link
        fedilink
        English
        arrow-up
        2
        ·
        8 hours ago

        My brain kept prodding me to do the (x + k - 1) / k integer ceil trick at first, which wasn’t quite right :/

  • codeinabox@programming.dev
    link
    fedilink
    English
    arrow-up
    4
    ·
    21 hours ago

    Python

    Here’s my initial solution in Python for part one.

    import sys
    
    def distance(start, next):
        if start == next:
            return 6
    
        sequence = "roygbv"
        startIndex = sequence.find(start)
        nextIndex = sequence.find(next, startIndex)
    
        if nextIndex >= 0:
            return nextIndex - startIndex
        else:
            return len(sequence) - startIndex + sequence.find(next)
    
    def total_distance(sequence):
        total = 0
        lastChar = "r"
    
        for char in sequence:
            total += distance(lastChar, char)
            lastChar = char
    
        return total
    
    if __name__ == '__main__':
        print(total_distance(sys.argv[1]))
    
  • obliviousdusk@lemmy.zip
    link
    fedilink
    arrow-up
    10
    ·
    1 day ago

    Rust

    fn parts(input: &str) -> (String, String) {
        let targets = input.chars().flat_map(|c| "_oygbvr".find(c)).collect_vec();
    
        let part1 = 6 * targets
            .iter()
            .tuple_windows()
            .filter(|(a, b)| b <= a)
            .count()
            + targets.last().unwrap();
    
        let part2 = targets.iter().min().unwrap() + 6 * (input.len() - 1);
    
        (part1.to_string(), part2.to_string())
    }
    

    For part 1, I count the number of wrap-arounds as consecutive colors that are not increasing and check the last color to see where mod 6 it ends up. To make this work nicely, I moved the r to the end of the colors and added a dummy color at the beginning, such that a single r ends up at 6.

    For part 2, the resulting program would always be a sorted list of colors, in the reverse order of my character list. Most characters will add 6 to the total. Only at the transition between color segments is the distance reduced, and the reduction corresponds exactly to the difference between the color values. Because the program must be sorted, the total reduction is the difference between the first and the last color. And since the sorting order would be the reverse of my character list, I end up with the inverse difference (mod 6) and add it instead of subtracting.

    • mcmodknower@programming.dev
      link
      fedilink
      English
      arrow-up
      2
      ·
      1 day ago

      In the end I edited my solution to solve part 2 in the same way, but in the case that the input does not contain an ‘o’, it should be -4 instead of -5, since the difference between the first and last color would be 2 (and not 1). Similar for more missing letters. But as always the AOC inputs are (seemingly) made with the intent of not hitting such cases.

  • Camille@lemmy.ml
    link
    fedilink
    arrow-up
    5
    ·
    1 day ago

    Hare

    The first part wasn’t hard, I just had to check the maths twice. But I’ve spent way too much time on part 2 realizing that my function to find the optimal instruction iterated in reverse order, leading me to choose either a +6 move or the worst available one hehehe.

    part 1
    type waypoint = enum uint {
    	red = 0,
    	orange = 1,
    	yellow = 2,
    	green = 3,
    	blue = 4,
    	violet = 5,
    	__modulo = 6,
    };
    
    type state = struct {
    	current: waypoint,
    	distance: uint,
    };
    
    fn u8_to_waypoint(c: u8) (waypoint | aoc::error) = {
    	switch (c) {
    	case 'r' => return waypoint::red;
    	case 'o' => return waypoint::orange;
    	case 'y' => return waypoint::yellow;
    	case 'g' => return waypoint::green;
    	case 'b' => return waypoint::blue;
    	case 'v' => return waypoint::violet;
    	case =>
    	     return fmt::asprintf("Unknown input '{}'", c)!: aoc::error;
    	};
    };
    
    fn goto_next(st: *state, w: waypoint) void = {
    	if (st.current < w) {
    		st.distance += w - st.current;
    	} else {
    		st.distance += waypoint::__modulo - st.current + w;
    	};
    
    	st.current = w;
    };
    
    fn part1(scan: *bufio::scanner) (int | aoc::error) = {
    	let st = state { current = waypoint::red, distance = 0 };
    	const prgm = bufio::read_line(scan)!: []u8;
    
    	for (let insn .. prgm) {
    		goto_next(&st, u8_to_waypoint(insn)?);
    	};
    
    	return st.distance: int;
    };
    
    part 2
    fn waypoint_to_u8(w: waypoint) u8 = {
    	switch (w) {
    	case waypoint::red => return 'r';
    	case waypoint::orange => return 'o';
    	case waypoint::yellow => return 'y';
    	case waypoint::green => return 'g';
    	case waypoint::blue => return 'b';
    	case waypoint::violet => return 'v';
    	case =>
    	     return 'a'; // unreachable
    	};
    };
    
    fn next_wp(w: waypoint) waypoint = switch (w) {
    	case waypoint::red => return waypoint::violet;
    	case waypoint::orange => return waypoint::red;
    	case waypoint::yellow => return waypoint::orange;
    	case waypoint::green => return waypoint::yellow;
    	case waypoint::blue => return waypoint::green;
    	case waypoint::violet => return waypoint::blue;
    	case waypoint::__modulo => return waypoint::__modulo;
    };
    
    fn find_insn(w: waypoint, prgm: *[]u8) bool = {
    	let insn = waypoint_to_u8(w);
    	match (bytes::index(*prgm, insn)) {
    	case void =>
    		return false;
    	case let idx: size =>
    		const left = prgm[0..idx];
    		const right = prgm[idx+1..];
    		append(left, right...)!;
    		*prgm = left;
    		return true;
    	};
    };
    
    fn goto_farthest(st: *state, prgm: *[]u8) void = {
    	let best_insn = st.current;
    
    	for (true) {
    		if (find_insn(best_insn, prgm))
    		   break;
    
    		best_insn = next_wp(best_insn);
    	};
    
    	goto_next(st, best_insn);
    };
    
    fn part2(scan: *bufio::scanner) (int | aoc::error) = {
    	let st = state { current = waypoint::red, distance = 0 };
    	let prgm = bufio::read_line(scan)!: []u8;
    
    	for (len(prgm) > 0) {
    		goto_farthest(&st, &prgm);
    	};
    
    	return st.distance: int;
    };
    
  • eta@feddit.org
    link
    fedilink
    English
    arrow-up
    3
    ·
    edit-2
    17 hours ago

    Elixir

    I thought about this a bit and realised that modulo math could probably help with this repeating pattern. So I transformed the letters to numbers, like on a clock. For part 2 I just sorted the program in descending order, since you start at 0 (or rather 6) and want to go as far as possible for all the remaining instructions.

    solution
    #!/usr/bin/env elixir
    
    defmodule AOC do
    
    def getProgNums(prog) do
    	String.graphemes(prog)
    	|> Enum.map(
    		&Map.get(%{"r"=>6,"o"=>1,"y"=>2,"g"=>3,"b"=>4,"v"=>5}, &1, &1)
    	)
    end
    
    def part1(prog) do
    	move(AOC.getProgNums(prog), 0, 0)
    end
    
    def move([], acc, _pos) do
    	acc
    end
    
    def move([n | rest], acc, pos) do
    	case rem(n-pos, 6) do
    		r when r <= 0 -> move(rest, acc + r + 6, n)
    		r -> move(rest, acc + r, n)
    	end
    end
    
    def part2(prog) do
    	AOC.getProgNums(prog)
    	|> Enum.sort(:desc)
    	|> move(0,0)
    end
    
    end # module
    
    input =
    	File.read!("input/day02.txt")
    	|> String.trim()
    
    IO.puts "Part 1 answer: #{AOC.part1(input)}"
    IO.puts "Part 2 answer: #{AOC.part2(input)}"
    
  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    23 hours ago

    C

    Based this on other solutions posted here.

    Usage:

    $ gcc main.c
    $ ./a.out input
    
    Part 1 solution
    #include <stdio.h>
    
    int get_index(char c)
    {
            int index;
            switch (c) {
                    case 'r':
                            index = 0;
                            break;
                    case 'o':
                            index = 1;
                            break;
                    case 'y':
                            index = 2;
                            break;
                    case 'g':
                            index = 3;
                            break;
                    case 'b':
                            index = 4;
                            break;
                    case 'v':
                            index = 5;
                            break;
            }
            return index;
    }
    
    int main(int argc, char** argv)
    {
            int t[6][6] = {
                    {6, 1, 2, 3, 4, 5},
                    {5, 6, 1, 2, 3, 4},
                    {4, 5, 6, 1, 2, 3},
                    {3, 4, 5, 6, 1, 2},
                    {2, 3, 4, 5, 6, 1},
                    {1, 2, 3, 4, 5, 6}
            };
            FILE *fp = fopen(argv[1], "r");
    
            int cur;
            int ch = 'r';
            int next = get_index(ch);
            int dist = 0;
    
            while (true) {
                    ch = fgetc(fp);
                    if (ch == EOF || ch == '\n') break;
                    cur = next;
                    next = get_index(ch);
                    dist += t[cur][next];
            }
            fclose(fp);
            printf("Distance travelled is: %i\n", dist);
            return 0;
    }
    

    Tried to keep it as small as possible, so obvious issues like not checking argc and not checking for letters other than roygbv. Which is pretty cursed because index is uninitialised, so get_index returns garbage, then t[cur][next] indexes into more garbage.

    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      2
      ·
      22 hours ago

      Pretty standard for aoc to not check for invalid inputs, and just write just enough code to get the result. Indexing off into the weeds would be very frustrating to debug though if it didnt crash :D

  • Tinwelint@lemmy.zip
    link
    fedilink
    English
    arrow-up
    5
    ·
    1 day ago

    ArkScript.

    (import aoc)
    (import std.Testing)
    
    (import std.List)
    (import std.String)
    
    (let dist (dict
      "r" 1
      "o" 2
      "y" 3
      "g" 4
      "b" 5
      "v" 6))
    
    (let solve (fun (data) {
      (mut output 0)
      (mut current "r")
    
      (list:forEach data (fun (waypoint) {
        (if (= waypoint current)
          (set output (+ output 6))
          {
            (let diff (- (@ dist waypoint) (@ dist current)))
            (set current waypoint)
            (if (> diff 0)
              (set output (+ output diff))
              (set output (+ output diff 6))) }) }))
    
      output }))
    
    (let optimize (fun (data) {
      (let counts (list:countOccurrences data))
      (let new (list:fold
        "rvbgyo"
        ""
        (fun (acc next)
          (if (not (@ counts next))
            acc
            (+
              acc
              (string:repeat next (@ counts next)))))))
    
      (solve new) }))
    
    (let data (head (aoc:readLines "input.txt")))
    
    (test:suite day2 {
      (test:case "part 1" {
        (test:eq (solve "obbvb") 16)
        (test:eq (solve "roygbv") 11)
        (test:eq (solve "vbgyor") 30)
        (test:eq (solve "vvvvvv") 35)
    
        (test:eq (solve data) 3681) })
    
      (test:case "part 2" {
        (test:eq (optimize "rybryb") 32)
        (test:eq (optimize "rrbbyy") 32)
        (test:eq (optimize "vrvgvg") 33)
        (test:eq (optimize "groovyyoyo") 55)
        (test:eq (optimize "roygbvroygbvroygbv") 103)
    
        (test:eq (optimize data) 5935) })})
    
    (if (> testing:_suite.failed 0)
      (sys:exit 1))
    
  • Ismail@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    1 day ago

    TXR

    (defun day02-pt1 ()
      (let ((pgm (file-get-string "02-input"))
            (col-num (pairlis "roygbv" 1..7)))
        (cdr (reduce-left (tb ((pos . dist) nxpos) 
                            (cons nxpos (+ dist (wrap 1 6 (- nxpos pos)))))
                          (map (lopip (assoc col-num) cdr) pgm)
                          '(1 . 0)))))
    

    I didn’t solve part 2 programmatically. I simply used Emacs’ 'count-matches' command to count occurrences of the 5 characters (not 6, as one of them never occurs!), and calculated the answer manually.

  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    7
    ·
    edit-2
    1 day ago

    Uiua

    Part one was simple enough, but part two was a little fiddlier to implement. I might have a think about whether there’s a tidier implementation. [edit: yes there was :-)]

    Brief explanation

    Both parts increment the index at each step and then consider the indexes of the various colours, mod 6. Part two could be even simpler: -5×6⧻"rybryb" but that is probably so big a clue even in Uiua that it deserves to be spoilered.

    C ← "roygbv"
    S ← ∧(+◿6⊸˜-⊙+₁)
    S⊙0⋉C"obbvb"          # Part 1
    +1S⇌⍆◿6-1⊙0⋉C"rybryb" # Part 2
    

    Run it for yourself!

  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    1 day ago

    Lua

    For part one I created a linked list of the colours, then pointed the “next” value of the last node to the first node, so that I could call node.next forever. Other people used mod which seems like a much more sensible solution. Oh well at least I learned about linked lists in lua!

    usage lua robots.lua < input

    Part1
    Dots = "roygbv"
    
    function List.insert(node, value)
            node = {next = node, data = value}
            return node
    end
    
    function List.makeloop(head)
            local node = head
            local prev = nil
            while node do
                    prev = node
                    node = node.next
            end
            prev.next = head
    end
    
    function List.move(char, list)
            local incr = 0
            local node = list
            if node.data == char then
                    incr = 6
            else
                    while node.data ~= char do
                            incr = incr + 1
                            node = node.next
                    end
            end
            return incr, node
    end
    
    list = nil
    dist = 0
    
    for i=#Dots,1,-1 do
            list = List.insert(list, Dots:sub(i,i))
    end
    
    List.makeloop(list)
    
    local line = io.read("*line")
    for i=1,#line do
            incr, list = List.move(line:sub(i,i), list)
            dist = dist + incr
    end
    
    print(dist)
    

    For part 2 I just counted how many times each colour appeared, then printed them out in the correct order. I learned that iterating over a table in Lua using pairs(table) is non-deterministic because it is a implemented using hashes, so I had to have another table to explicitly store the order.

    usage: lua rearrange.lua < input | lua robot.lua

    Part2
    local counts = {r=0, o=0, y=0, g=0, b=0, v=0}
    local order = {"r", "v", "b", "g", "y", "o"}
    
    local line = io.read("*line")
    
    for i = 1, #line do
            local char = line:sub(i, i)
            counts[char] = counts[char] + 1
    end
    
    for _, key in ipairs(order) do
            for i = 1, counts[key] do
                    io.write(key)
            end
    end
    

    I also learned a valuable lesson in version control when attempting to use tee to debug and deleted my entire solution.

  • CameronDev@programming.devOPM
    link
    fedilink
    arrow-up
    5
    ·
    1 day ago

    Rust

    spoiler
        const LOOKUP_TABLE: [[i32; 6]; 6] = [
            [6, 1, 2, 3, 4, 5],
            [5, 6, 1, 2, 3, 4],
            [4, 5, 6, 1, 2, 3],
            [3, 4, 5, 6, 1, 2],
            [2, 3, 4, 5, 6, 1],
            [1, 2, 3, 4, 5, 6],
        ];
    
    ...
        #[test]
        fn test_y2026_day2_part2() {
            let input = include_str!("../../input/2026/day_2.txt");
    
            let input = include_str!("../../input/2026/day_2.txt");
            let mut moves: Vec<u8> = input
                .trim()
                .chars()
                .map(|c| match c {
                    'r' => 6,
                    'o' => 1,
                    'y' => 2,
                    'g' => 3,
                    'b' => 4,
                    'v' => 5,
                    _ => panic!(),
                })
                .collect();
            moves.sort();
    
            let mut total = 0;
            let mut last = 0u8;
            moves.iter().rev().for_each(|next| {
                total += LOOKUP_TABLE[last as usize % 6][*next as usize % 6];
                last = *next;
            });
    
            println!("Total: {total}")
        }
    

    Suprisingly easy one this time as well. Part two probably could be optimised down to a simple multiplication i suspect, but no need when this is pretty damn fast anyway.

  • Gobbel2000@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    1 day ago

    Rust

    Solved part 2 simply by sorting the string appropriately and then calling part 1 again.

    Solution
    const fn color_to_n(color: u8) -> u8 {
        match color {
            b'r' => 0,
            b'o' => 1,
            b'y' => 2,
            b'g' => 3,
            b'b' => 4,
            b'v' => 5,
            _ => panic!("Unknown color"),
        }
    }
    
    fn distance(a: u8, b: u8) -> u8 {
        (5 + b - a) % 6 + 1 // Modulo with range from 1 to n instead of 0 to n-1
    }
    
    fn part1(input: String) {
        let mut pos = 0;
        let mut dist = 0;
        for col in input.trim().bytes().map(color_to_n) {
            dist += u32::from(distance(pos, col));
            pos = col;
        }
        println!("{dist}");
    }
    
    fn part2(input: String) {
        let mut sorted = input.trim().as_bytes().to_owned();
        sorted.sort_by_key(|&c| 6 - distance(0, color_to_n(c))); // Sort first r, then v, b, g, y, o
        part1(String::from_utf8(sorted).unwrap());
    }
    
    util::aoc_main!();