Day 3: Foggy Forest

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

  • Pyro@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    8 hours ago

    Python

    Chose to do part 1 and 2 very differently.

    • Part 1 runs checks pairs of trees along the diagonal to see if they form opposite corners of a square.
    • Part 2 turns every segment formed by 2 trees by 90 degrees to see if it is the side of a square.
    click to see code
    from collections import defaultdict
    from itertools import combinations
    
    def part1(data: str):
        trees = set()                       # set of all trees
        trees_on_diag = defaultdict(list)   # list of trees grouped by their diagonal
        for i, line in enumerate(data.splitlines()):
            for j, ch in enumerate(line):
                if ch == '#':
                    trees.add((i, j))
                    # trees can be grouped using a single integer into its down-right diagonal
                    # if you use i-j, you get:
                    #   0   -1  -2  -3
                    #   1   0   -1  -2
                    #   2   1   0   -1
                    #   3   2   1   0
                    trees_on_diag[i-j].append((i, j))
    
        squares = 0
        # for trees in the same diagonal, try combinations of each and see if they form opposite corners of a square
        for diag_trees in trees_on_diag.values():
            for (x1, y1), (x2, y2) in combinations(diag_trees, r=2):
                if (x1, y2) in trees and (x2, y1) in trees:
                    squares += 1
    
        return squares
    
    def part2(data: str):
        trees = set()   # set of all trees
        for i, line in enumerate(data.splitlines()):
            for j, ch in enumerate(line):
                if ch == "#":
                    trees.add((i, j))
    
        squares = 0
        # for all tree combinations, we will assume that they form a side of square and check if that is valid
        for t1, t2 in combinations(trees, r=2):
            i1, j1 = t1
            i2, j2 = t2
    
            # the difference between the trees in i, j dimensions
            di, dj = (i1 - i2), (j1 - j2)
            # since we don't know which direction that 90d angle should be to continue the square, we will try both ways
            turns = (
                (-dj, di), # left hand 90d turn
                (dj, -di), # right hand 90d turn
            )
    
            for turn_i, turn_j in turns:
                # new points after turning from both original point (you could also turn twice)
                t3, t4 = (i1 + turn_i, j1 + turn_j), (i2 + turn_i, j2 + turn_j)
    
                # if any points are not trees, we go on
                if t3 not in trees:
                    continue
                if t4 not in trees:
                    continue
                squares += 1
    
        # since we tried to make every segment a square, we counted each square 4 times
        # this is because each side of the square will find it once in one of its turns
        return squares // 4
    
    
  • Chais@sh.itjust.works
    link
    fedilink
    arrow-up
    2
    ·
    20 hours ago

    Python

    from pathlib import Path
    from typing import Any
    
    
    def parse_input(input: str) -> list[str]:
        return input.strip().splitlines()
    
    
    def part_one(input: str) -> int:
        p = parse_input(input)
        s = 0
        for m in range(len(p) - 1):
            for n in range(len(p) - 1):
                for l in range(1, len(p) - max(n, m)):
                    if p[m][n] == p[m + l][n] == p[m][n + l] == p[m + l][n + l] == "#":
                        s += 1
        return s
    
    
    def part_two(input: str) -> int:
        p = parse_input(input)
        s = 0
        for m in range(len(p) - 1):
            for n in range(len(p) - 1):
                for l in range(1, len(p) - max(n, m)):
                    for o in range(l):
                        if p[m][n + o] == p[m + l - o][n] == p[m + o][n + l] == p[m + l][n + l - o] == "#":
                            s += 1
        return s
    
    
    if __name__ == "__main__":
        input = Path("input").read_text("utf-8")
        print(part_one(input))
        print(part_two(input))
    
  • eco_game@discuss.tchncs.de
    link
    fedilink
    arrow-up
    2
    ·
    21 hours ago

    Kotlin

    Part 1 was simple enough, for every node, check to the bottom and right in equal distance if nodes are found there, then search for the fourth node at r + offset and c + offset. Initially I was scared this would take long, but it runs instantly so good enough for me.

    It’s only day 3 and I already took over 24 h for part 2… Not proud, takes roughly 5 seconds to run, looks horrible, but works:
    For every node, draw vectors to all nodes “beneath” it (lower rows), then find orthogonal pairs, and for each pair search for the fourth point again. I’m actually reasonably happy with the idea, I assume if you implement this better it may be pretty fast too.

    Solution
    class Day03 : Puzzle {
    
        private lateinit var grid: List<List<Boolean>>
        private lateinit var nodes: Set<Pair<Int, Int>>
    
        override fun readFile() {
            val input = readInputFromFile(2026, 3, false)
            grid = input.lines().filter { it.isNotBlank() }
                .map { line -> line.map { it == '#' } }
            nodes = input.lines().filter { it.isNotBlank() }
                .mapIndexedNotNull { r, row ->
                    val points = row.mapIndexedNotNull { c, cell -> if (cell == '#') c else null }
                        .map { c -> r to c }
                    return@mapIndexedNotNull points.ifEmpty { null }
                }.flatten()
                .toSet()
        }
    
        override fun solvePartOne(): String {
            return nodes.flatMap { (r, c) -> findSquares(r, c) }.toSet().size.toString()
        }
    
        override fun solvePartTwo(): String {
            val squares = mutableSetOf<Square>()
            for ((nr, nc) in nodes) {
                val vectors = nodes.filter { (r, _) -> r > nr }
                    .map { (r, c) -> r - nr to c - nc }
                vectors.mapNotNull { (vr, vc) ->
                        val orth = vectors.filter { (dr, dc) -> dr * vr + dc * vc == 0 && dr * dr + dc * dc == vr * vr + vc * vc }
                        if (orth.size > 1) throw IllegalStateException("orthogonal count is over 1: $orth")
                        return@mapNotNull if (orth.isEmpty()) null else setOf((vr to vc), orth.first())
                    }.toSet()
                    .forEach { set ->
                        val corner = set.reduce { (ar, ac), (br, bc) -> nr + ar + br to nc + ac + bc }
                        if (corner in nodes) {
                            squares.add(Square(
                                Point(nr, nc),
                                Point(nr + set.first().first, nc + set.first().second),
                                Point(nr + set.last().first, nc + set.last().second),
                                Point(corner.first, corner.second),
                            ))
                        }
                    }
                squares.addAll(findSquares(nr, nc)) // add normal squares too
            }
            return squares.size.toString()
        }
    
        private fun findSquares(r: Int, c: Int): List<Square> {
            return (1..<min(grid.size - r, grid[r].size - c)) // possible step width, towards bottom right
                .map { it to listOf(grid[r][c + it], grid[r + it][c], grid[r + it][c + it]) } // map to grid points
                .filter { corners -> corners.second.all { it } } // only take offsets where the other 3 points are corners
                .map { (offset, _) -> Square(r, c, offset) }     // map offset -> 4 corners -> square
        }
    
        data class Square(val a: Point, val b: Point, val c: Point, val d: Point) {
            constructor(r: Int, c: Int, offset: Int) : this(
                Point(r, c),
                Point(r, c + offset),
                Point(r + offset, c),
                Point(r + offset, c + offset),
            )
        }
    }
    

    full code on Codeberg

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

    PHP

    My first full-time job was mostly PHP, and since that was in the noughties, I wanted to see what had changed. Not enough! It’s still very inconsistent, although the new features do take some of the pain away.

    Unfortunately, I found the new pipe operator to frequently involve enough boilerplate that it was cleaner not to bother, .e.g $x |> (fn($s) => str_replace(" ", "-", $s)). NerdFont’s triangle ligature is quite satisfying, at least!

    Going from p1 to p2 meant looking at 69773 -> 193909310 candidate squares, although I’m sure there’s simple optimisations to be made. 2.3 secs to run, so I wasn’t waiting around.

    function parse($input) {
        $ar = [];
        $lines = explode("\n", $input);
        foreach ($lines as $line) {
            $ar[] = array_map(fn($ch) => ($ch == '#'), str_split($line));
        }
        return $ar;
    }
    
    function run($input) {
        $num_orth = 0;
        $num_diag = 0;
        $trees = parse($input);
        // start at SW, for cleaner maths
        for ($y = count($trees)    - 1; $y >= 1; $y--) {
        for ($x = count($trees[0]) - 1; $x >= 1; $x--) {
            // bounding box
            $max = max($x, $y);
            // sweep in, checking other corners
            for ($i = $max; $i > 0; $i--) {
            // but also skew
            for ($o = 0; $o < $max; $o++) {
                if (($trees[$y      ][$x      ] ?? false) && // root (SE)
                    ($trees[$y-$i   ][$x   -$o] ?? false) && // NE
                    ($trees[$y-$i+$o][$x-$i-$o] ?? false) && // NW
                    ($trees[$y   +$o][$x-$i   ] ?? false))   // SW
                {
                    if (!$o) {$num_orth++;}
                    $num_diag++;
                }
            }
            }
        }
        }
        return [$num_orth, $num_diag];
    }
    
  • shape_warrior_t@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    23 hours ago

    Rust

    Spent most of the time writing a 2D grid abstraction and writing up the solution, rather than actually solving the problem. In fact, had the problem solved before Day 4 came out, and just took until now to figure out a reasonable way to explain it in my writeup.

    Basically: do a double for loop through the set of all trees. For part 1, the two trees should be the top-left and bottom-right corners of the square (check to make sure they’re properly diagonal from each other, and that the other two corners have trees). For part 2, the two trees should be consecutive corners of the square (find the other two corners by continuing the walk around the square, and make sure they have trees). In part 2, we need to divide by 4 to account for duplicates (each square is counted once per side). Solution completes “instantly” in release mode, so I’m pretty satisfied with the performance, at least compared to a lot of other people in this thread.

    Relevant parts of code
    pub fn part_1(input: &str) -> Num {
        let map: Grid<Tile> = input.parse().unwrap();
        let trees: Vec<_> = map
            .coordinates()
            .filter(|&index| map[index] == Tile::Tree)
            .collect();
        iproduct!(&trees, &trees)
            .filter(|&(&(x0, y0), &(x1, y1))| {
                x1 - x0 == y1 - y0
                    && x0 < x1
                    && y0 < y1
                    && map[(x1, y0)] == Tile::Tree
                    && map[(x0, y1)] == Tile::Tree
            })
            .count() as _
    }
    
    pub fn part_2(input: &str) -> Num {
        let map: Grid<Tile> = input.parse().unwrap();
        let trees: Vec<_> = map
            .coordinates()
            .filter(|&index| map[index] == Tile::Tree)
            .collect();
        let rooted_squares = iproduct!(&trees, &trees)
            .filter_map(|(&t0, &t1)| {
                if t0 == t1 {
                    return None;
                }
                let d0 = sub(t1, t0);
                assert_eq!(t1, add(t0, d0));
                let d1 = rotate(d0);
                let t2 = add(t1, d1);
                let d2 = rotate(d1);
                let t3 = add(t2, d2);
                let d3 = rotate(d2);
                assert_eq!(t0, add(t3, d3));
                assert_eq!(d0, rotate(d3));
                (map.get(t2) == Some(&Tile::Tree) && map.get(t3) == Some(&Tile::Tree))
                    .then_some((t0, t1, t2, t3))
            })
            .count();
        assert_eq!(rooted_squares % 4, 0);
        (rooted_squares / 4) as _
    }
    
    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      2
      ·
      18 hours ago

      For pt2, another way to handle/prevent duplicates is to remove the trees as you go. Most of my performance issues went away in release mode, i got pt2 to 2-3ms, which is good enough. Would prefer <1ms, but further optimising is basically just taking someone elses solution, so I’ll live with my inadequacy :D

  • Strlcpy@2@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    22 hours ago

    C

    I intend to make this more efficient by anchoring the rotations on [x,y], so I can quickly skip if it’s not #, but I’m too tired now to fix the boundary conditions for that. Otherwise fairly happy!

    Edit: done! Much better now

    Original version
    int
    main()
    {
    	static char grid[144][144];
    	int sz=0, p1=0, p2=0, x,y,i,r;
    
    	while (fgets(grid[sz], sizeof(*grid), stdin)) {
    		sz++;
    		assert(sz<144);
    	}
    
    	for (y=0; y<sz-1; y++)
    	for (x=0; x<sz-1; x++)
    	for (i=1; y+i<sz && x+i<sz; i++) {
    		p1 += grid[y][x] == '#' &&
    		      grid[y][x+i] == '#' &&
    		      grid[y+i][x] == '#' &&
    		      grid[y+i][x+i] == '#';
    		
    		for (r=0; r<i; r++)
    			p2 += grid[y][x+r] == '#' &&
    			      grid[y+r][x+i] == '#' &&
    			      grid[y+i-r][x] == '#' &&
    			      grid[y+i][x+i-r] == '#';
    	}
    
    	printf("03: %d %d\n", p1, p2);
    }
    
    int
    main()
    {
    	static char grid[144][144];
    	int sz=0, p1=0,p2=0, x,y, u,v, hit;
    
    	while (fgets(grid[sz], sizeof(*grid), stdin)) {
    		sz++;
    		assert(sz<144);
    	}
    
    	for (y=0; y<sz-1; y++)
    	for (x=0; x<sz-1; x++) {
    		if (grid[y][x] != '#')
    			continue;
    		for (u=1; x+u<sz && y+u<sz; u++)
    		for (v=0; x-v>=0 && y+u+v<sz; v++) {
    			hit = grid[y+v][x+u] == '#' &&
    			      grid[y+u][x-v] == '#' &&
    			      grid[y+v+u][x+u-v] == '#';
    			p1 += hit && !v;
    			p2 += hit;
    		}
    	}
    
    	printf("03: %d %d\n", p1, p2);
    }
    
  • VegOwOtenks@lemmy.world
    link
    fedilink
    arrow-up
    7
    ·
    2 days ago

    ARM Assembly

    Runs instantly. Executable is 46K of disk. I could probably use dynamic allocation to reduce the executable size. But I’m happy, satisfied and not sure whether I can do this tomorrow.

    a lot of code
    .global _start // Declare the entry point of the program
    .align 4      // Align the next instruction to a 4-byte boundary
    
    _start:
      adr x19, trees
      adr x20, grid
      bl parse
      add x21, x21, #1 // account for the newline stride
      bl count
      mov x0, x23
      bl print
      mov x0, x24
      bl print
      b exit
    
    print:
      adr x1, print_buf
      
      mov w2, #10
      strb w2, [x1, #15]!
      mov x4, x1
      mov x5, #1
      
    print_format:
      udiv x1, x0, x2
      smull x3, w1, w2
      sub x3, x0, x3
      add x3, x3, #48
      strb w3, [x4, #-1]!
      add x5, x5, #1
      mov x0, x1
      cbnz x0, print_format
    
    print_write:
      mov x0, #1
      mov x1, x4
      mov x2, x5
      mov x8, #64 // write
      svc 0
    
      ret
    
    // x19: array, x20: grid, x21: nrows & ncols
    // out: x23 squares, x24 rot-squares
    count:
      sub x19, x19, #8 // outer iteration pointer
      mov x23, #0
      mov x24, #0
    
    count_outer_head:
      b count_outer_tail
    
    count_outer_body:
    count_inner_head:
      mov x22, x19 // inner iteration pointer
      b count_inner_tail
    
    count_inner_body:
      cmp w0, w2 // point2.y <= point1.y
      b.gt count_inner_tail // continue
      cmp w3, w1 // point2.x <= point1.x
      b.le count_inner_tail // continue
    
      sub w4, w2, w0 // y-difference
      sub w5, w3, w1 // x-difference
    
      // bot-left
      add w6, w0, w5 // bot-left.y = point1.y + x-diff
      sub w7, w1, w4 // point1.x - y-diff
      mul w8, w6, w21
      add w8, w8, w7
    
      cmp w6, w21
      b.ge count_inner_tail // bot-left.y >= nrows
      cmp w7, #0
      b.lt count_inner_tail // bot-left.x < 0
      ldrb w9, [x20, w8, sxtw]
      cbz w9, count_inner_tail // bot-left is not tree
    
      // bot-right
      add w6, w2, w5 // bot-right.y = top-right.y + x-diff
      sub w7, w3, w4 // bot-right.x = top-right.x - y-diff
      mul w8, w6, w21
      add w8, w8, w7
    
      cmp w6, w21
      b.ge count_inner_tail // bot-right.y >= nrows
      cmp w7, #0
      b.lt count_inner_tail // < 0
      ldrb w9, [x20, w8, sxtw]
      cbz w9, count_inner_tail
    
    count_success:
      add x24, x24, #1
      cbnz w4, count_inner_tail
      add x23, x23, #1
      
    
    
    count_inner_tail:
      ldp w2, w3, [x22, #8]!
      cmp w2, #-1 // sentinel value
      b.eq count_outer_tail
      b count_inner_body
    
    count_outer_tail:
      ldp w0, w1, [x19, #8]!
      cmp w0, #-1 // sentinel value
      b.ne count_outer_body
      ret
    
    parse:
      mov x21, #0 // row
      mov x22, #0 // col
      mov x23, x19 // array + i - 1
      sub x23, x23, #8
    
    // parse_read:
      mov x0, #0 // stdin
      mov x1, x20
      mov x2, #32768
      mov x8, #0x3F // read
      svc 0
      cbz x0, exit_fail // end of file
    
      mov x1, #0 // i
    parse_loop_top:
      ldrb w2, [x20, x1]
      cmp w2, #35
      b.eq parse_tree
      cmp w2, #10
      b.eq parse_newline
      b parse_dot
    parse_tree:
      mov w2, #1 // nonzero for tree
      stp w21, w22, [x23, #8]!
      b parse_loop_bot
    parse_newline:
      add x21, x21, #1
      mov x22, #-1 // fallthrough for zero
    parse_dot:
      mov w2, #0 // zero for non-tree
    parse_loop_bot:
      strb w2, [x20, x1]
      add x22, x22, #1
      add x1, x1, #1
      cmp x1, x0
      b.ne parse_loop_top
    
    parse_done:
      mov x22, #-1
      stp w22, w22, [x23, #8]
      ret
    
    exit:
      mov x0, #0            // x0 = 0 (exit code)
    exit_fail:
      mov x8, #0x5D         // x8 = 93 (sys_exit)
      svc 0
    
    .section .data
    print_buf: .fill 16
    trees: .fill 3*4096
    grid: .fill 8*4096
    
  • eta@feddit.org
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    1 day ago

    Elixir

    For part 1 I iterated over the lists and took some time figuring out what the end condition for this should actually be. Not really proud of this part but it works.

    So for part 2 I started over and did it with an approach kind of using a starting point, vector to a second point and then calculating point 3 and 4 from there. Then each point is checked wether it’s out of bounds and if it has a tree planted there. It’s taking a few seconds to complete so it’s not running really fast but I like the approach more than my part 1 and it could probably be optimised by rearranging some checks so it stop checking earlier.

    Edit: Rearranging checks doesn’t do much, this approach is just slow. It’s probably better to get the coordinates for all trees and work with that as some other solutions did.

    solution
    #!/usr/bin/env elixir
    
    defmodule AOC do
    
    def getData(inputStr) do
    	inputStr
    	|> String.split("\n", trim: true)
    	|> Enum.map(fn s -> String.graphemes(s) end)
    end
    
    def part1(data) do
    	0..length(data)-2
    	|> Enum.map(
    		fn r ->
    			0..length(Enum.at(data,0))-2
    			|> Enum.map(
    				fn c ->
    					case Enum.at(Enum.at(data,r),c) do
    						"#" -> checkPos(data, r, c)
    						_ -> 0
    					end
    				end
    			)
    			|> Enum.sum()
    		end
    	)
    	|> Enum.sum()
    end
    
    def checkPos(data, r, c) do
    	ub = min(length(data)-1-r, length(Enum.at(data,0))-1-c)
    	c+1..c+ub
    	|> Enum.map(
    		fn c2 ->
    			dist = c2 - c
    			if Enum.at(Enum.at(data,r),c2) == "#" and
    			Enum.at(Enum.at(data,r+dist),c) == "#" and
    			Enum.at(Enum.at(data,r+dist),c2) == "#" do
    				1
    			else
    				0
    			end
    		end
    	)
    	|> Enum.sum()
    end
    
    def part2(data) do
    	for r <- 0..length(data)-2, c <- 0..length(data)-2 do
    		case Enum.at(Enum.at(data,r),c) do
    			"#" -> checkPos2(data, r, c)
    			_ -> 0
    		end
    	end
    	|> Enum.sum()
    end
    
    def checkPos2(data, r, c) do
    	for dr <- 1..length(data)-1, dc <- -c..0 do
    		{r2, c2, r3, c3} = {r+dr, c+dc, r-dc, c+dr}
    		{r4, c4} = {r3+dr, c3+dc}
    		if r3 < length(data) and c3 < length(data) and
    		r4 < length(data) and c4 < length(data) do
    			if Enum.at(Enum.at(data,r2),c2) == "#" and
    			Enum.at(Enum.at(data,r3),c3) == "#" and
    			Enum.at(Enum.at(data,r4),c4) == "#" do
    				1
    			else
    				0
    			end
    		else
    			0
    		end
    	end
    	|> Enum.sum()
    end
    
    end # module
    
    input = AOC.getData(File.read!("input/day03.txt"))
    IO.puts "part 1 #{AOC.part1(input)}"
    IO.puts "part 2 #{AOC.part2(input)}"
    
  • Ismail@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    2 days ago

    TXR

    The idea behind solving part 1 is to consider every horizontal pair of hash characters as potentially forming the top edge of a square. The assumption is proven if an aligned pair of hash chars exists in a lower row.

    Part 1
    (defun day03 ()
      (let ((grid (file-get-lines "03-input")))
        (put-line `1: @(pt1 grid)`)
        (put-line `2: @(pt2 grid)`)))
    
    (defun pt1 (grid)
      (let ((side (len grid))
            (count 0))
        (each ((line grid)
               (row 0..side))
          (let ((cols (let ((pos -1))
                        (gun (set pos (search-str line "#" (succ pos)))))))
            (each ((left (conses cols)))
              (each ((right (cdr left)))
                (let ((base (+ row (- right (car left)))))
                  (when (and (< base side)
                             (eq #\# (mref grid base (car left)))
                             (eq #\# (mref grid base right)))
                    (inc count)))))))
        count))
    

    This solution to part 2 is as brutal as brute-force can be. Every rotation of every possible square is checked and the tally is increased if hash chars are present at its corners.

    (defun pt2 (grid)
      (let ((side (len grid))
            (count 0))
        (each ((gap 1..(succ side)))
          (each* ((x1 0..(- side gap))
                  (x2 (+ x1 gap)))
            (each* ((y1 0..(- side gap))
                    (y2 (+ y1 gap)))
              (each ((offset 0..gap))
                (macrolet ((tree-at (x y)
                             ^(eq #\# (mref grid ,y ,x))))
                  (when (and (tree-at (+ x1 offset) y1)
                             (tree-at x2 (+ y1 offset))
                             (tree-at (- x2 offset) y2)
                             (tree-at x1 (- y2 offset)))
                    (inc count)))))))
        count))
    
  • Camille@lemmy.ml
    link
    fedilink
    arrow-up
    6
    ·
    2 days ago

    Hare

    Not too complicated but my solution is clearly inefficient. For part 1 I built a horizontal segments for each pair of trees on each line and when the length of a segment fit in the height of the currently read map, I check if the same segment exists $length rows higher.

    part 1
    type hsegment = struct {
    	column: uint,
    	length: uint,
    };
    
    fn hseg(col: uint, length: uint) hsegment = hsegment {
    	column = col,
    	length = length,
    };
    
    fn seg_eq(lhs: hsegment, rhs: hsegment) bool = {
    	return lhs.column == rhs.column && lhs.length == rhs.length;
    };
    
    fn get_all_segments(line: []u8) []hsegment = {
    	let segs: []hsegment = alloc([], 0)!;
    	let found: []uint = alloc([], 0)!;
    	defer free(found);
    
    	for (let col = len(line) - 1; col < len(line); col -= 1) {
    		const c = line[col];
    		if (c == '#') {
    			for (let fnd .. found) {
    				append(segs, hseg(col: uint, fnd-col: uint))!;
    			};
    			append(found, col: uint)!;
    		};
    	};
    
    	return segs;
    };
    
    fn find_segment(line: []hsegment, seg: hsegment) bool = {
    	for (let s .. line) {
    		if (seg_eq(s, seg))
    			return true;
    	};
    	return false;
    };
    
    fn part1(scan: *bufio::scanner) (int | aoc::error) = {
    	let segs: [][]hsegment = alloc([], 0)!;
    	defer free(segs);
    
    	let squares = 0;
    	let linenb = 0;
    
    	for (true) {
    		match (bufio::read_line(scan)!) {
    		case io::EOF => break;
    		case let line: []u8 => {
    			const cursegs = get_all_segments(line);
    			append(segs, cursegs)!;
    
    			const height = len(segs);
    			for (let seg .. cursegs) {
    				if (seg.length >= height)
    					continue;
    
    				const otherline = segs[height - seg.length - 1];
    				if (find_segment(otherline, seg)) {
    					squares += 1;
    				};
    			};
    		};
    		};
    
    		linenb += 1;
    	};
    
    	for (let s .. segs) {
    		free(s);
    	};
    	return squares;
    };
    

    For part 2 I created a real list of points, wrote functions to do all the math around points and defining squares. I build a list of all the known squares and finally compute its length. At some point it didn’t work because I only checked the length of the sides of my squares, not the diagonals, so I had too many squares but couldn’t tell what was wrong. I doubted the sort algorithm so hard I rewrote a bubble sort, to be sure lmao

    part 2
    type point = struct {
    	x: int,
    	y: int,
    };
    
    fn p(x: int, y: int) point = point { x = x, y = y };
    fn p_eq(lhs: point, rhs: point) bool = {
    	return lhs.x == rhs.x && lhs.y == rhs.y;
    };
    
    fn p_cmp(a: point, b: point) int = {
    	const dx = b.x - a.x;
    	if (dx != 0)
    		return dx;
    
    	return b.y - a.y;
    };
    
    // Good old squared hypothenuse, no need to sqrt it.
    fn distance(lhs: point, rhs: point) int = {
    	const dx = rhs.x - lhs.x;
    	const dy = rhs.y - lhs.y;
    	return dx*dx + dy*dy;
    };
    
    // Given an original point orig and two points A and B, find the fourth point
    // that make it a square and return true if any.
    //
    // If distance(A, orig) != distance(B, orig), the function returns false.
    fn find_fourth(
    	orig: point,
    	a: point,
    	b: point,
    	points: []point,
    ) nullable * point = {
    	if (p_eq(orig, a) || p_eq(orig, b) || p_eq(a, b))
    		return null;
    
    	const dist = distance(orig, a);
    	const dist2 = distance(a, b);
    
    	if (dist != distance(orig, b))
    		return null;
    
    	for (let p .. points) {
    		if (p_eq(p, orig) || p_eq(p, a) || p_eq(p, b))
    			continue;
    
    		if (
    			distance(a, p) == dist
    			&& distance(b, p) == dist
    			&& dist2 == distance(orig, p)
    		) {
    			return &p;
    		};
    	};
    
    	return null;
    };
    
    fn add_all_points(points: *[]point, line: []u8, linenb: uint) []point = {
    	let curpoints: []point = alloc([], 0)!;
    
    	for (let col = 0u; col < len(line): uint; col += 1) {
    		if (line[col] == '#') {
    			const pnt = p(linenb: int, col: int);
    			append(points, pnt)!;
    			append(curpoints, pnt)!;
    		};
    	};
    
    	return curpoints;
    };
    
    type square = [4]point;
    
    fn make_square(p1: point, p2: point, p3: point, p4: point) square = {
    	let sq = [p1, p2, p3, p4]: square;
    
    	for (let i = 0z; i < 3; i += 1) {
    		for (let j = i + 1; j < 4; j += 1) {
    			if (p_cmp(sq[i], sq[j]) > 0) {
    				let tmp = sq[i];
    				sq[i] = sq[j];
    				sq[j] = tmp;
    			};
    		};
    	};
    
    	return sq;
    };
    
    fn add_square(squares: *[]square, sq: square) void = {
    	for (let s .. squares) {
    		if (
    			p_eq(s[0], sq[0])
    			&& p_eq(s[3], sq[3])
    		) {
    			return;
    		};
    	};
    	append(squares, sq)!;
    };
    
    fn search_them_all(
    	squares: *[]square,
    	curpoints: []point,
    	points: []point,
    ) void = {
    	const pnb = len(points);
    	for (let cur .. curpoints) {
    		for (let i = 0z; i < pnb - 1; i += 1) {
    			for (let j = i; j < pnb; j += 1) {
    				const a = points[i];
    				const b = points[j];
    				match (find_fourth(cur, a, b, points)) {
    				case null => continue;
    				case let p: *point =>
    					const sq = make_square(cur, a, b, *p);
    					add_square(squares, sq);
    				};
    			};
    		};
    	};
    };
    
    fn part2(scan: *bufio::scanner) (int | aoc::error) = {
    	let points: []point = alloc([], 0)!;
    	let linenb = 0u;
    	let squares: []square = alloc([], 0)!;
    	defer free(squares);
    
    	for (true) {
    		match (bufio::read_line(scan)!) {
    		case io::EOF => break;
    		case let line: []u8 => {
    			const curpoints = add_all_points(&points, line, linenb);
    			defer free(curpoints);
    
    			search_them_all(&squares, curpoints, points);
    		};
    		};
    
    		linenb += 1;
    	};
    
    	return len(squares): int;
    };
    
  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    2 days ago

    Lua

    Part1 solution: For each line I generated an array of tree pairs by encoding the position of the first tree and distance to another tree as a comma seperated string. Eg. #...# would be encoded as {"1,5"} and ##..# would be {"1,2", "1,5"}. Then for each pair of trees I check if row - width contains a matching string.

    Part 1
    local pairsTable = {}
    local line = io.read("*line")
    local forestWidth = #line
    local count = 0
    
    function hasMatchingPair(encodedData, rowToCheck)
            if rowToCheck < 1 then
                    return false
            end
            local row = pairsTable[rowToCheck]
            for _,data in ipairs(row.data) do
                    if encodedData == data then
                            return true
                    end
            end
    end
    
    local row = 1
    while true do
            local positionsRow = {}
            local positions = {}
    
            for i=1,forestWidth do
                    local char = line:sub(i,i)
                    if char == '#' then
                            table.insert(positions, i)
                    end
            end
            if #positions > 1 then
                    for i=1,#positions-1 do
                            for j=i+1,#positions do
                                    pos = positions[i]
                                    width = positions[j]-positions[i] + 1
                                    encodedData = tostring(pos) .. "," .. tostring(width)
                                    table.insert(positionsRow, encodedData)
                                    if hasMatchingPair(encodedData, row - width + 1) then
                                            count = count + 1
                                    end
                            end
                    end
            end
    
            table.insert(pairsTable, {row = row, data = positionsRow})
            line = io.read("*line")
            if line == nil then break end
            row = row + 1
    end
    print("Total is: " .. count)
    

    Coming from C to Lua is a bit annoying, because a lot of the data structure is abstracted from you, so things don’t always work how I expect them to.

    Edit: finally finished part 2. My approach was to identify all the trees (a) that are equidistant from two other trees (b,c) AND have a third tree (d) that corresponds to the sum of the vectors to the other two trees. Then I check that |a->d| == |b->c| then I think it is a square…

    ngl I found that quite challenging. Good thing I quit my day job.

    Elapsed CPU time: 0.682239 seconds

    solution
    local trees = {}
    local line = io.read("*line")
    local forestWidth = #line
    local squareCount = 0
    local row = 1
    
    -- Looks back at visited trees, gets a vectors from current tree to all previous trees
    function checkAllPreviousTrees(trees, row, col)
            local distances = {}
            for _,tree in pairs(trees) do
                    -- calculate distance to previous tree
                    i = tree.pos.row - row
                    j = tree.pos.col - col
                    dist = i^2 + j^2
                    if distances[dist] then
                            table.insert(distances[dist], {row = i, col = j})
                    else
                            distances[dist] = {{row = i, col = j}}
                    end
            end
            return distances
    end
    
    -- Loop over input, hashing tree positions
    while true do
            for col=1,forestWidth do
                    local distances = {}
                    local id
                    if line:sub(col,col) == '#' then
                            distances = checkAllPreviousTrees(trees, row, col)
                            id = col + (forestWidth * (row-1))
                            trees[id] = {
                                    pos = {row = row, col = col},
                                    distances = distances
                            }
                    end
            end
            line = io.read("*line")
            if line == nil then break end
            row = row + 1
    end
    
    function diagonalsAreEqual(A, B)
            local vecAB = {-A.row + B.row, -A.col + B.col}
            local vecPC = {A.row + B.row, A.col + B.col}
            local magAB = vecAB[1]^2 + vecAB[2]^2
            local magPC = vecPC[1]^2 + vecPC[2]^2
            if magAB == magPC then
                    print("Found a square")
                    return true
            end
            return false
    end
    
    -- iterate over vectors, if two or more vectors have the same magnitude then
    -- compare the magnitude of their diagonals
    for id,tree in pairs(trees) do
            for distance,vectors in pairs(tree.distances) do
                    local pos = tree.pos
                    if #vectors > 1 then
                            local diagonal = {}
                            local vectorSum
                            for i=1,#vectors-1 do
                                    for j=i+1,#vectors do
                                            diagonal.row = vectors[i].row + vectors[j].row + pos.row
                                            diagonal.col = vectors[i].col + vectors[j].col + pos.col
                                            vectorSum = diagonal.col + (forestWidth * (diagonal.row-1))
                                            -- if there is a tree on the diagonal
                                            if trees[vectorSum] then
                                                    if diagonalsAreEqual(vectors[i], vectors[j]) then
                                                            squareCount = squareCount + 1
                                                    end
                                            end
                                    end
                            end
                    end
            end
    end
    
  • obliviousdusk@lemmy.zip
    link
    fedilink
    arrow-up
    3
    ·
    2 days ago

    Rust

    fn parts(input: &str) -> (String, String) {
        let grid = input.lines().map(|l| l.as_bytes()).collect_vec();
        let trees = (0..grid.len())
            .cartesian_product(0..grid[0].len())
            .filter_map(|(y, x)| Some((x as i32, y as i32)).filter(|_| grid[y][x] == b'#'))
            .collect::<HashSet<_>>();
    
        let pairs = trees.iter().cartesian_product(trees.iter());
    
        let (part1, part2) = pairs
            .map(|((x0, y0), (x1, y1))| ((*x0, *y0), (*x1 - *x0, *y1 - *y0)))
            .filter(|((x, y), (dx, dy))| {
                (dx > &0 && dy >= &0)
                    && trees.contains(&(x - dy, y + dx))
                    && trees.contains(&(x + dx - dy, y + dy + dx))
            })
            .map(|(_, (_, dy))| ((dy == 0) as i32, 1))
            .reduce(|a, b| (a.0 + b.0, a.1 + b.1))
            .unwrap();
    
        (part1.to_string(), part2.to_string())
    }
    
  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    6
    ·
    edit-2
    1 day ago

    Uiua

    Really just brute force, but it only takes a few seconds (see below). Looking forward to seeing what I missed. [Edit: Tidied up logic.]

    "#.###\n.##.#\n##.##\n.#.#.\n.##.#"
    ⧅<2⊚=@#⊜∘⊸≠@\n
    M  ← /+∊+⊸≡(¤×1_¯1⇌⊸/-) # Does edge have matching edge?
    P₁ ← M ▽=1⊸≡(⧻◴⊢⍉)      # Only pick horz. edges.
    P₂ ← ÷2M                # All edges, div by two as both slopes will be found.
    ⊃P₁ P₂
    

    I know no-one cares apart from me now, but inspired by some discussion on the Uiua discord, I used complex numbers to simplify calculating the opposite edges, and got rid of expensive rows operations, at the expense of some slightly more convoluted code. But! the following now solves with live data in <0.2 seconds native, 0.4 in Uiua Pad. Marked Experimental as subscripted transform is still bleeding edge.

    # Experimental!
    "#.###\n.##.#\n##.##\n.#.#.\n.##.#" # Replace with live data :-)
    ⧅₂<⊸⊚=@#⊜∘⊸≠@\n                     # Find trees, keep and pair up.
    M  ← /+/×⍉⍜♭₂⬚0⊡+≡¤⍉⍜(ℂ°⊟|×i)/-⊸⍉   # For every edge, find lower edge, check both points have trees.
    P₁ ← M ▽=0⊢⍉/-⊸⍉₂                   # Filter pairs on same row (i.e. top edges)
    P₂ ← ÷₂M                            # All edges, div by 2 as both slopes will be found.
    &p ⍜now(⊃P₁ P₂)
    

    Try it here!

  • janAkali@programming.dev
    link
    fedilink
    arrow-up
    8
    ·
    edit-2
    2 days ago

    Nim

    Not a hard problem today, but I still managed to over-complicate part 2 in my head. Then it finally clicked, and I solved it basically the same way as part 1.

    Part 1 - we find all pairs of corners, consider them as the left side of the square and then transpose them to where the right side of the square should be. Then check if those points do exist. I used hashset here, because I was lazy to do bounds checks, reading original grid is probably faster?
    Part 2 - same as part 1, but second corner can also be to the left of first corner.

    Runtime: 24.5 ms 8.6 ms

    type Vec2 = tuple[x,y:int]
    
    proc checkExists(grid: seq[string], x,y: int): bool =
      x < grid[0].len and y < grid.len and grid[y][x] == '#'
    
    proc solve(input: string): AOCSolution[int, int] =
      let grid = input.splitLines()
      var points: seq[Vec2]
      for y, line in grid:
        for x, c in line:
          if c == '#': points.add (x,y)
    
      for i, (x,y) in points:
        for (tx,ty) in points.toOpenArray(i+1, points.high):
          let (dx,dy) = (tx-x, ty-y)
          if dx <= 0 and grid.checkExists(x+dy, y-dx) and grid.checkExists(tx+dy, ty-dx):
            if dx == 0:
              inc result.part1
            inc result.part2
    
    older slower version
    type Vec2 = tuple[x,y:int]
    
    proc solve(input: string): AOCSolution[int, int] =
      var list: seq[Vec2]
      for y, line in enumerate input.splitLines():
        for x, c in line:
          if c == '#':
            list.add (x,y)
    
      var points = list.toHashSet()
      for i, (x,y) in list:
        for (tx,ty) in list.toOpenArray(i+1, list.high):
          let (dx,dy) = (tx-x, ty-y)
          if dx <= 0 and (x+dy, y-dx) in points and (tx+dy, ty-dx) in points:
            if dx == 0:
              inc result.part1
            inc result.part2
    

    Full code on Codeberg: solution.nim

    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      4
      ·
      2 days ago

      I like this approach much better than mine, I waste so much time walking around the grid to find the next corner, instead of checking the known trees.

      • addie@feddit.uk
        link
        fedilink
        arrow-up
        3
        ·
        2 days ago

        Indeed; very nice. Saves wasting loads of time checking for ‘every possible grid and skew’ like I was doing, since it only checks possibilities, and would scale very well to truly enormous grids of trees.

          • janAkali@programming.dev
            link
            fedilink
            arrow-up
            3
            ·
            2 days ago

            hashset lookup is just brutally slow for some reason

            You’re probably doing way too many hashing checks, my version prunes a lot of incorrect pairs (where second corner is above or to the right of the first) cheaply.

            But you also don’t need hashset here at all, you can just index into the existing grid e.g. grid[y][x] == '#'.

            • CameronDev@programming.devOPM
              link
              fedilink
              arrow-up
              1
              ·
              edit-2
              2 days ago

              Priming the hash checks didnt help, but now you mention it, just indexing into the grid is very obvious…

              Edit: down to 22ms, completely dropped hashset. Still not quite happy, but getting there!