this post was submitted on 13 Dec 2023
13 points (88.2% liked)

Advent Of Code

770 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
13
submitted 11 months ago* (last edited 11 months ago) by Ategon to c/advent_of_code
 

Day 13: Point of Incidence

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)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


πŸ”’ Thread is locked until there's at least 100 2 star entries on the global leaderboard

πŸ”“ Unlocked

top 17 comments
sorted by: hot top controversial new old
[–] [email protected] 6 points 11 months ago (2 children)

Haskell

This was fun and (fairly) easy! Off-by-one errors are a likely source of bugs here.

import Control.Monad
import Data.List
import Data.List.Split
import Data.Maybe

score d pat = ((100 *) <$> search pat) `mplus` search (transpose pat)
  where
    search pat' = find ((d ==) . rdiff pat') [1 .. length pat' - 1]
    rdiff pat' i =
      let (a, b) = splitAt i pat'
       in length $ filter (uncurry (/=)) $ zip (concat $ reverse a) (concat b)

main = do
  input <- splitOn [""] . lines <$> readFile "input13"
  let go d = print . sum . map (fromJust . score d) $ input
  go 0
  go 1

Line-seconds score: 0.102 πŸ˜‰

[–] [email protected] 2 points 11 months ago

Very pretty again!

[–] [email protected] 1 points 11 months ago* (last edited 11 months ago) (1 children)
[–] [email protected] 2 points 11 months ago* (last edited 11 months ago)

Yep, that's it. (A totally scientific and non-fakeable measurement! /s)

[–] [email protected] 4 points 11 months ago* (last edited 3 months ago) (1 children)

Python

from .solver import Solver


def is_mirrored_x(pattern: set[tuple[int, int]], max_x: int, max_y: int,
                  x_mirror: int, desired_errors: int = 0) -> bool:
  min_x = max(0, 2 * x_mirror - max_x)
  max_x = min(max_x, 2 * x_mirror)
  errors = 0
  for y in range(max_y):
    for x in range(min_x, x_mirror):
      mirrored = 2 * x_mirror - x - 1
      if (x, y) in pattern and (mirrored, y) not in pattern:
        errors += 1
      if (x, y) not in pattern and (mirrored, y) in pattern:
        errors += 1
      if errors > desired_errors:
        return False
  return errors == desired_errors

def is_mirrored_y(pattern: set[tuple[int, int]], max_x: int, max_y: int,
                  y_mirror: int, desired_errors: int = 0) -> bool:
  min_y = max(0, 2 * y_mirror - max_y)
  max_y = min(max_y, 2 * y_mirror)
  errors = 0
  for x in range(max_x):
    for y in range(min_y, y_mirror):
      mirrored = 2 * y_mirror - y - 1
      if (x, y) in pattern and (x, mirrored) not in pattern:
        errors += 1
      if (x, y) not in pattern and (x, mirrored) in pattern:
        errors += 1
      if errors > desired_errors:
        return False
  return errors == desired_errors

def find_mirror_axis(pattern: set[tuple[int, int]], max_x: int, max_y: int,
                     desired_errors: int = 0) -> tuple[None, int]|tuple[int, None]:
  for possible_x_mirror in range(1, max_x):
    if is_mirrored_x(pattern, max_x, max_y, possible_x_mirror, desired_errors):
      return possible_x_mirror, None
  for possible_y_mirror in range(1, max_y):
    if is_mirrored_y(pattern, max_x, max_y, possible_y_mirror, desired_errors):
      return None, possible_y_mirror
  raise RuntimeError('No mirror axis found')

class Day13(Solver):

  def __init__(self):
    super().__init__(13)
    self.patterns: list[set[tuple[int, int]]] = []
    self.dimensions: list[tuple[int, int]] = []

  def presolve(self, input: str):
    patterns = input.rstrip().split('\n\n')
    for pattern in patterns:
      lines = pattern.splitlines()
      points: set[tuple[int, int]] = set()
      max_x = 0
      max_y = 0
      for y, line in enumerate(lines):
        max_y = max(max_y, y)
        for x, char in enumerate(line):
          max_x = max(max_x, x)
          if char == '#':
            points.add((x, y))
      self.patterns.append(points)
      self.dimensions.append((max_x + 1, max_y + 1))

  def solve_first_star(self) -> int:
    sum = 0
    for pattern, (max_x, max_y) in zip(self.patterns, self.dimensions, strict=True):
      mirror_x, mirror_y = find_mirror_axis(pattern, max_x, max_y)
      sum += (mirror_x or 0) + (mirror_y or 0) * 100
    return sum

  def solve_second_star(self) -> int:
    sum = 0
    for pattern, (max_x, max_y) in zip(self.patterns, self.dimensions, strict=True):
      mirror_x, mirror_y = find_mirror_axis(pattern, max_x, max_y, 1)
      sum += (mirror_x or 0) + (mirror_y or 0) * 100
    return sum
[–] cvttsd2si 4 points 11 months ago (1 children)

Scala3

// i is like
//  # # # # #
//   1 2 3 4
def smudgesAround(i: Int, s: List[List[Char]]): Long =
    val toEdge = math.min(i, s.size - i)
    (0 until toEdge).map(e => s(i - e - 1).lazyZip(s(i + e)).count(_ != _)).sum

def symmetries(g: List[List[Char]], smudges: Int) =
    val rows = (1 until g.size).filter(smudgesAround(_, g) == smudges)
    val g2 = g.transpose
    val cols = (1 until g2.size).filter(smudgesAround(_, g2) == smudges)
    100*rows.sum + cols.sum

def task1(a: List[String]): Long = a.chunk(_ == "").map(g => symmetries(g.map(_.toList), 0)).sum
def task2(a: List[String]): Long = a.chunk(_ == "").map(g => symmetries(g.map(_.toList), 1)).sum

[–] [email protected] 2 points 11 months ago (1 children)

Wouldn't this code fail in a case like this? Because you count different lines, not different characters in the lines, right? Or am I missing something? Thanks (Let's ignore column symmetry for the sake of example).

##
..
..
..

(I think you will get answer 100, but the answer is 300)

But for sure after seeing this I have to learn Scala.

[–] cvttsd2si 2 points 11 months ago* (last edited 11 months ago) (1 children)

On your example, my code produces 301, which matches your 300 ignoring column symmetry (and 0 for task2, as there is no way to smudge a single cell to create symmetry).

Let me explain the code real quick: What smudgesAround does is compute the number of tiles you would need to change to create a symmetry around index i. First, toEdge is the number of tiles to the nearest edge, everything after that will be reflected outside the grid and won't matter. Then, for each actually relevant distance, we compare the rows/columns this distance from i. By zipping them, we create an Iterator that first yields the pair of first entries, then the pair of second entries, and so on. On each pair we apply a comparison, to count the number of entries which did not match. This is the number of smudges we need to fix to get these rows/columns to match. Summing over all relevant pairs of rows/columns, we get the total number of smudges to make i a mirror line. In symmetries, we just check each i, for task1 we want a mirror line without smudges and for task2 we want a mirror line for exactly one

You can also make this quite a bit shorter, if you want to sacrifice some more readability:

def compute(a: List[String], sm: Int) =
    a.chunk(_ == "").map(_.map(_.toList)).map(g => Seq(g, g.transpose).map(s => (1 until s.size).filter(i => (0 until math.min(i, s.size - i)).map(e => s(i - e - 1).zip(s(i + e)).count(_ != _)).sum == sm).sum).zip(Seq(100, 1)).map(_ * _).sum).sum

def task1(a: List[String]): Long = compute(a, 0)
def task2(a: List[String]): Long = compute(a, 1)
[–] [email protected] 2 points 11 months ago

Oh, I see, I for some reason switched zip operation with β€œcreate pair/tuple” operation in my head. Thanks for clarification.

[–] [email protected] 4 points 11 months ago

Rust

Part 2 turned out easier than I thought initially. My code assumes that there is only 1 mirror in each field which means I don't have to remember where the smudge is, I just have to find a mirror line where the two halves differ at exactly one spot.

[–] [email protected] 3 points 11 months ago

C

Implementing part 1 with a bunch of for loops made me wonder about elegant NumPy solutions but then part 2 came along and it was a perfect fit! Just change a flag to a counter and remove the if-match-early-exit.

https://github.com/sjmulder/aoc/blob/master/2023/c/day13.c

int main()
{
	static char g[32][32];
	int p1=0,p2=0, w,h, x,y,i, nmis;
	
	while (!feof(stdin)) {
		for (h=0; ; h++) {
			assert(h < (int)LEN(*g));
			if (!fgets(g[h], LEN(*g), stdin)) break;
			if (!g[h][0] || g[h][0]=='\n') break;
		}

		assert(h>0); w = strlen(g[0])-1;
		assert(w>0);

		for (x=1; x
[–] [email protected] 3 points 11 months ago

Dart

Just banging strings together again. Simple enough once I understood that the original reflection may also be valid after desmudging. I don't know if we were supposed to do something clever for part two, but my part 1 was fast enough that I could just try every possible smudge location and part 2 still ran in 80ms

bool reflectsH(int m, List p) => p.every((l) {
      var l1 = l.take(m).toList().reversed.join('');
      var l2 = l.skip(m);
      var len = min(l1.length, l2.length);
      return l1.take(len) == l2.take(len);
    });

bool reflectsV(int m, List p) {
  var l1 = p.take(m).toList().reversed.toList();
  var l2 = p.skip(m).toList();
  var len = min(l1.length, l2.length);
  return 0.to(len).every((ix) => l1[ix] == l2[ix]);
}

int findReflection(List p, {int butNot = -1}) {
  var mirrors = 1
      .to(p.first.length)
      .where((m) => reflectsH(m, p))
      .toSet()
      .difference({butNot});
  if (mirrors.length == 1) return mirrors.first;

  mirrors = 1
      .to(p.length)
      .where((m) => reflectsV(m, p))
      .toSet()
      .difference({butNot ~/ 100});
  if (mirrors.length == 1) return 100 * mirrors.first;

  return -1; //never
}

int findSecondReflection(List p) {
  var origMatch = findReflection(p);
  for (var r in 0.to(p.length)) {
    for (var c in 0.to(p.first.length)) {
      var pp = p.toList();
      var cells = pp[r].split('');
      cells[c] = (cells[c] == '#') ? '.' : '#';
      pp[r] = cells.join();
      var newMatch = findReflection(pp, butNot: origMatch);
      if (newMatch > -1) return newMatch;
    }
  }
  return -1; // never
}

Iterable> parse(List lines) => lines
    .splitBefore((e) => e.isEmpty)
    .map((e) => e.first.isEmpty ? e.skip(1).toList() : e);

part1(lines) => parse(lines).map(findReflection).sum;

part2(lines) => parse(lines).map(findSecondReflection).sum;
[–] Deebster 3 points 11 months ago* (last edited 11 months ago)

I decided to use string comparison for some reason, which meant part two wasn't as quick as it would have been.

use std::{cmp, fs, iter};

fn transpose(rows: &[&str]) -> Vec {
    (0..rows[0].len())
        .map(|i| {
            let bytes: Vec<_> = (0..rows.len()).map(|j| rows[j].as_bytes()[i]).collect();
            String::from_utf8(bytes).unwrap()
        })
        .collect()
}

fn reflection_value(rows: &[&str]) -> Option {
    'row_loop: for i in 0..(rows.len() - 1) {
        if rows[i] != rows[i + 1] {
            continue;
        }
        // we have an initial match
        let other_matches = cmp::min(i, rows.len() - 2 - i);
        for j in 1..=other_matches {
            if rows[i - j] != rows[i + 1 + j] {
                continue 'row_loop;
            }
        }
        return Some(i as u32 + 1);
    }
    None
}

fn summary(file_path: &str) -> u32 {
    fs::read_to_string(file_path)
        .expect("Can't read input file")
        .split("\n\n")
        .map(|s| {
            let rows: Vec<&str> = s.split('\n').collect();

            if let Some(v) = reflection_value(&rows) {
                v * 100
            } else {
                let cols_owned: Vec = transpose(&rows);
                let cols: Vec<&str> = cols_owned.iter().map(|s| s.as_str()).collect();
                reflection_value(&cols).expect("No reflections found")
            }
        })
        .sum()
}

fn str_diff(str1: &str, str2: &str) -> u32 {
    iter::zip(str1.chars(), str2.chars())
        .map(|(s1, s2)| if s1 == s2 { 0 } else { 1 })
        .sum()
}

fn smudged_reflection_value(rows: &[&str]) -> Option {
    for i in 0..(rows.len() - 1) {
        let num_cmps = cmp::min(i, rows.len() - 2 - i);
        let errs: u32 = (0..=num_cmps)
            .map(|j| str_diff(rows[i - j], rows[i + 1 + j]))
            .sum();

        if errs != 1 {
            continue;
        }
        return Some(i as u32 + 1);
    }
    None
}

fn smudged_summary(file_path: &str) -> u32 {
    fs::read_to_string(file_path)
        .expect("Can't read input file")
        .split("\n\n")
        .map(|s| {
            let rows: Vec<&str> = s.split('\n').collect();

            if let Some(v) = smudged_reflection_value(&rows) {
                v * 100
            } else {
                let cols_owned: Vec = transpose(&rows);
                let cols: Vec<&str> = cols_owned.iter().map(|s| s.as_str()).collect();
                smudged_reflection_value(&cols).expect("No reflections found")
            }
        })
        .sum()
}

fn main() {
    println!(" normal: {}", summary("d13/input.txt"));
    println!("smudged: {}", smudged_summary("d13/input.txt"));
}
[–] [email protected] 2 points 11 months ago* (last edited 11 months ago)

Nim

Part 1: For part 1 I just compare rows, then transpose matrix and compare rows again.
Part 2: For part 2 I compare rows and get symmetry type for each comparison: symmetric(==), almost symmetric (1 smudge), not symmetric (2+ difference). Then I just use two booleans to make sure we found exactly one smudge in each mirror.

Total runtime: 0.3 ms
Puzzle rating: 6/10
Code: day_13/solution.nim

[–] [email protected] 1 points 11 months ago (1 children)

Nim

This one was a nice change of pace after the disaster of day 12. For part 1 I kept a list of valid column indexes, and checked those columns in each row for reflections, eliminating columns from the list as I went. To find vertical reflections, I just transposed the grid first.

Part 2 looked daunting at first, but I just needed to add a smudges counter to each column candidate, eliminating them when their counter reaches 2. For scoring, just count the 1-smudge columns.

[–] [email protected] 1 points 11 months ago

Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn't work well for people on different instances. Try fixing it like this: [email protected]