this post was submitted on 12 Dec 2025
14 points (100.0% liked)

Advent Of Code

1199 readers
1 users here now

An unofficial home for the advent of code community on programming.dev! Other challenges are also welcome!

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.

Everybody Codes is another collection of programming puzzles with seasonal events.

EC 2025

AoC 2025

Solution Threads

M T W T F S S
1 2 3 4 5 6 7
8 9 10 11 12

Visualisations Megathread

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 2 years ago
MODERATORS
 

Day 12: Christmas Tree Farm

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

top 14 comments
sorted by: hot top controversial new old
[–] Avicenna@programming.dev 2 points 6 days ago* (last edited 6 days ago)

After reading multiple papers on stuff like polyomino and coverings etc over the weekend, I sat down to formulate an ILP approach. All the way through I had at the back of my mind "surely he would not expect people to solve something which requires reading research papers, there must be some angle to this which makes it easier". I don't think I have ever been more right in my life and I am really glad I made the obvious fail and succeed checks based on areas lol.

import numpy as np
import itertools as it
from pathlib import Path
from time import time

cwd = Path(__file__).parent.resolve()

def timing(f):
  def wrap(*args, **kw):
    ts = time()
    result = f(*args, **kw)
    te = time()
    print(f"func{f.__name__} args: {args} took: {te-ts:.4f} sec")

    return result
  return wrap

def parse_input(file_path):
  with file_path.open("r") as fp:
    data = list(map(str.strip, fp.readlines()))

  objects = []
  for i in range(6):
    i0 = data.index(f"{i}:")
    obj = np.array(list(map(list, data[i0+1:i0+4])))
    obj[obj=='#']=1
    obj[obj=='.']=0
    objects.append(obj.astype(int))

  i0 = data.index("5:")+5
  placements = []

  for line in data[i0:]:
    dims = list(map(int, line.split(':')[0].split('x')))
    nobjs = list(map(int, line.split(': ')[-1].split(' ')))
    placements.append((dims, nobjs))

  return objects, placements

@timing
def solve_problem(file_name):

  ref_objects, placements = parse_input(Path(cwd, file_name))
  areas = [np.count_nonzero(obj==1) for obj in ref_objects]

  counter_succesful = 0

  for grid_shape, nobjs in placements:
    obj_area = np.sum(np.array(nobjs)*areas)
    grid_area = np.prod(grid_shape)
    worse_area =  np.sum(np.array(nobjs)*9)

    if worse_area<=grid_area:
      counter_succesful += 1
      continue

    if obj_area>grid_area:
      continue

  return counter_succesful

if __name__ == "__main__":

  assert solve_problem("input") == 583
[–] mykl@lemmy.world 4 points 1 week ago* (last edited 1 week ago)

Obviously very spoilery code, if you dare read it closely. try it here

It feels very anticlimactic to be ending so early in the month, but see you all next year!

# AOC 2025 day 12 - Packing parcels
▽⊸≡◇˜∊@x⊜□⊸≠@\n&fras"AOC2025day12.txt"
/+<⊙×₉≡◇(⊓/×/+⊃↙↘2⊜⋕¬⊸∊": x")

[–] Pyro@programming.dev 3 points 1 week ago* (last edited 1 week ago) (2 children)

Python

You got me good, Eric.

hintThink of the simplest check you can make for a region.

click to view code

# This does not work for the sample :D

def solve(data: str):
    # split input
    blocks = data.split("\n\n")
    shape_blocks = blocks[:-1]
    region_block = blocks[-1]

    # for every shape, get the number of occupied cells
    shape_area = []
    for shape_block in shape_blocks:
        shape_area.append(shape_block.count('#'))

    fit_regions = 0

    # for every region, check if the area is sufficient to fit all shapes
    for region_data in region_block.splitlines():
        size_data, shape_data = region_data.split(': ')

        # get region size
        m, n = [int(dim) for dim in size_data.split('x')]

        # get area needed to fit all shapes, without considering arrangement
        area_needed = 0
        for id, freq in enumerate(map(int, shape_data.split(' '))):
            area_needed += shape_area[id] * freq
        
        # if the region area is sufficient, count it as a fit (!!!)
        if m * n > area_needed:
            fit_regions += 1
    
    return fit_regions

[–] Deebster@programming.dev 4 points 1 week ago* (last edited 1 week ago) (1 children)

Mild spoilers ahead, but you're reading the solutions thread.

I was just doing some preliminary checking of the data on my phone with Nushell (to see how much my ageing laptop would suffer) when I discovered there weren't any non trivial cases.

Normally I get the test data working before trying the input data, this is definitely teaching me the value of investigating the data before heading down into the code mines.

Unfortunately I can't get the second star yet because I missed a few days.

[–] Pyro@programming.dev 2 points 1 week ago* (last edited 1 week ago) (1 children)

I actually did a lot of optimizations before I had to give up and search what I was missing. I did have a look at my input data, but still wouldn't make the connection because in my mind, any solution had to work for the sample too.

[–] Deebster@programming.dev 2 points 1 week ago

Yeah, it's quite a mean trick really - kinda a big middle finger to anyone who does TDD

[–] CameronDev@programming.dev 2 points 1 week ago (1 children)

spoilerI had an feeling it would be trivial, but didnt think it would be that trivial. I got the answer without even parsing the shapes, just called them all 9.

[–] Pyro@programming.dev 2 points 1 week ago

Tap for spoilerThat's very interesting because that was one of my early approaches too, but it actually gave me the wrong answer for my input!

[–] chunkystyles@sopuli.xyz 3 points 1 week ago* (last edited 1 week ago) (1 children)

Kotlin

Looking at the puzzle, I knew that I had no clue how to solve it. So I came here to see if I was missing something or if there were any hints.

And the hint I saw was to do the simplest check possible, so I gave it a shot.

And that got the test input wrong, but I ran it against the real input anyway just to see if it was right. And it was.

I think if I had gone on my instincts and just tried to solve this, I could have gone around in circles for hours or days trying to get it right.

fun main() {
    val input = getInput(12)
    val (gifts, regions) = parseInput1(input)
    var total = 0
    for (i in regions.indices) {
        val totalAreaOfGifts = regions[i].gifts.mapIndexed { index, count -> count * gifts[index].area }.sum()
        if (totalAreaOfGifts <= regions[i].area) {
            total++
        }
    }
    println(total)
}

data class Gift(val shape: List<List<Char>>, val area: Int)

data class Region(val width: Int, val height: Int, val area: Int, val gifts: List<Int>)

fun parseInput1(input: String): Pair<List<Gift>, List<Region>> {
    val gifts: MutableList<Gift> = mutableListOf()
    val regions: MutableList<Region> = mutableListOf()
    val lines = input.lines()
    lines.forEachIndexed { index, line ->
        if (line.contains(":")) {
            if (line.contains("x")) {
                val split = line.split(" ")
                val shape = split.first().replace(":", "").split("x")
                val width = shape.first().toInt()
                val height = shape.last().toInt()
                regions.add(
                    Region(
                        width,
                        height,
                        width * height,
                        split.slice(1..<split.size).map { str -> str.toInt() })
                )
            } else {
                var nextBlankLineIndex = 0
                for (i in index + 1..<lines.size) {
                    if (lines[i].isBlank()) {
                        nextBlankLineIndex = i
                        break
                    }
                }
                val shape = lines.slice(index + 1..<nextBlankLineIndex).map { it.toCharArray().toList() }
                val area = shape.flatten().filter { it == '#' }.size
                gifts.add(Gift(shape, area))
            }
        }
    }
    return gifts to regions
}
[–] Pyro@programming.dev 2 points 1 week ago

I struggled with optimizing this puzzle and had to go online to figure it out too, so I'm glad my hint helped you out.

[–] addie@feddit.uk 3 points 1 week ago (1 children)

C++

Hah, got me good too Mr Wastl. Was wondering how long this could possibly take to run - the worst-case is very bad indeed. This prints out the first "fit" it finds, for verification purposes, and keeps the successful ones in case they're needed for "part 2".

Merry Xmas, everyone.

#include <boost/describe.hpp>
#include <boost/describe/operators.hpp>
#include <boost/log/trivial.hpp>
#include <boost/unordered/unordered_flat_set.hpp>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>

namespace {

struct Point {
  int x, y;
};
BOOST_DESCRIBE_STRUCT(Point, (), (x, y))
using boost::describe::operators::operator==;

using Present = boost::unordered::unordered_flat_set<Point>;
using PresentList = std::vector<size_t>;

struct Tree {
  int width;
  int height;
  PresentList presents;
};
auto operator<<(std::ostream &o, const Tree &t) -> std::ostream & {
  o << t.width << 'x' << t.height << ": ";
  auto total = size_t{};
  for (auto &p : t.presents) {
    o << p << ' ';
    total += p;
  }
  return o << "(" << total << ")";
}

auto copy_if(const Present &in, Present &out, const Point &a, const Point &b) {
  if (in.contains(a))
    out.insert(b);
}

auto rotate(const Present &in) {
  auto out = Present{};
  copy_if(in, out, {0, 0}, {2, 0});
  copy_if(in, out, {1, 0}, {2, 1});
  copy_if(in, out, {2, 0}, {2, 2});
  copy_if(in, out, {0, 1}, {1, 0});
  copy_if(in, out, {1, 1}, {1, 1});
  copy_if(in, out, {2, 1}, {1, 2});
  copy_if(in, out, {0, 2}, {0, 0});
  copy_if(in, out, {1, 2}, {0, 1});
  copy_if(in, out, {2, 2}, {0, 2});
  return out;
}

auto hflip(const Present &in) {
  auto out = Present{};
  for (auto x = 0; x < 3; ++x)
    for (auto y = 0; y < 3; ++y)
      copy_if(in, out, {x, y}, {2 - x, y});
  return out;
}

auto vflip(const Present &in) {
  auto out = Present{};
  for (auto x = 0; x < 3; ++x)
    for (auto y = 0; y < 3; ++y)
      copy_if(in, out, {x, y}, {x, 2 - y});
  return out;
}

struct Puzzle {
  std::vector<Present> presents;
  std::vector<Tree> trees;
};

auto read() {
  auto rval = Puzzle{};
  auto ih = std::ifstream{"12.txt"};
  auto line = std::string{};
  for (auto i = 0; i < 6; ++i) {
    std::getline(ih, line); // number
    auto present = Present{};
    for (auto y = size_t{}; y < 3; ++y) {
      std::getline(ih, line);
      for (auto x = size_t{}; x < 3; ++x) {
        if (line.at(x) == '#')
          present.emplace(x, y);
      }
    }
    std::getline(ih, line); // following space
    rval.presents.push_back(std::move(present));
  }
  while (std::getline(ih, line)) {
    auto tree = Tree{};
    auto times = line.find('x');
    auto colon = line.find(':');
    tree.width = std::stoi(line.substr(0, times));
    tree.height = std::stoi(line.substr(times + 1, colon - times - 1));
    auto count = size_t{};
    auto ss = std::istringstream{line.substr(colon + 1)};
    while (ss >> count)
      tree.presents.push_back(count);
    rval.trees.push_back(std::move(tree));
  }
  return rval;
}

using Occupied = boost::unordered::unordered_flat_set<Point>;
using PresentFlips = boost::unordered::unordered_flat_set<Present>;
using PresentFlipsList = std::vector<PresentFlips>;

auto place_present(
    Occupied occupied,
    const Present &present,
    const Point &origin
) -> std::optional<Occupied> {
  for (const auto &point : present) {
    auto px = origin.x + point.x;
    auto py = origin.y + point.y;
    if (occupied.contains({px, py}))
      return {};
    occupied.insert({px, py});
  }
  return {occupied};
}

auto draw_occupied(const Tree &t, const Occupied &occupied) {
  for (auto x = 0; x < t.width; ++x) {
    for (auto y = 0; y < t.height; ++y) {
      if (occupied.contains({x, y}))
        std::cout << '#';
      else
        std::cout << '.';
    }
    std::cout << '\n';
  }
}

auto can_place(
    const Tree &tree,
    const PresentFlipsList &flips,
    Occupied occupied,
    PresentList list
) -> bool {
  auto j = size_t{};
  for (; j < list.size(); ++j) {
    if (list.at(j) > 0)
      break;
  }
  if (j == list.size()) {
    draw_occupied(tree, occupied);
    return true; // yeah!
  }
  list[j]--;

  for (auto x = 0; x < tree.width - 2; ++x)
    for (auto y = 0; y < tree.height - 2; ++y) {
      for (auto &flip : flips.at(j)) {
        auto test = place_present(occupied, flip, {x, y});
        if (!test.has_value())
          continue;
        auto works = can_place(tree, flips, test.value(), list);
        if (works)
          return true;
      }
    }
  return false;
}

auto part1(const Puzzle &puzzle) {
  auto possible = std::vector<Tree>{};
  for (const auto &tree : puzzle.trees) {
    auto area = size_t(tree.width * tree.height);
    auto used = size_t{};
    for (auto present = size_t{}; present < puzzle.presents.size(); ++present) {
      used += tree.presents.at(present) * puzzle.presents.at(present).size();
    }
    if (used > area)
      continue;
    possible.push_back(tree);
  }
  auto flips = PresentFlipsList{};
  for (auto j = size_t{}; j < puzzle.presents.size(); ++j) {
    auto flip = PresentFlips{};
    auto rotation = puzzle.presents.at(j);
    for (auto i = 0; i < 4; ++i) {
      flip.insert(rotation);
      flip.insert(hflip(rotation));
      flip.insert(vflip(rotation));
      flip.insert(hflip(vflip(rotation)));
      rotation = rotate(rotation);
    }
    BOOST_LOG_TRIVIAL(debug) << j << " has " << flip.size() << " flips";
    flips.push_back(std::move(flip));
  }
  auto confirmed = std::vector<Tree>{};
  for (auto &tree : possible)
    if (can_place(tree, flips, Occupied{}, tree.presents)) {
      BOOST_LOG_TRIVIAL(debug) << tree << " can be placed";
      confirmed.push_back(std::move(tree));
    } else {
      BOOST_LOG_TRIVIAL(debug) << tree << " can't be placed";
    }
  return confirmed.size();
}

} // namespace

auto main() -> int {
  auto puzzle = read();
  BOOST_LOG_TRIVIAL(info) << "Day 12: read " << puzzle.presents.size() << " / "
                          << puzzle.trees.size();
  BOOST_LOG_TRIVIAL(info) << "1:" << part1(puzzle);
}
[–] CameronDev@programming.dev 2 points 1 week ago (1 children)

Ha, that is beautiful. How long did it run for?

[–] addie@feddit.uk 3 points 1 week ago

For the test cases (ironically, the only difficult ones) it finds the solution for 1 basically instantly, 2 in 0.2 seconds, and checks all possibilities for 3 in about 18 seconds before rejecting it.

For the thousand 'puzzle' cases, about half are rejected since the area is simply too small for the presents in an instant. A possible solution is found for all of them in about 80 seconds, so about five per second.

I was concerned that the puzzle cases were about four times the area, and some of them had 255 presents (which might be the maximum stack depth in some languages - not C++, though). So maybe some of them would find a solution quickly, and excluding the worst might take ~ 4 times the size * 30 times the presents * 20 seconds = the best part of an hour. Multithreading it and hoping not too many of them were 'worst case', and I could leave my computer on overnight number-crunching it. Box packing is NP-complete and we need a 'true' answer rather than an approximation, so I couldn't see any better way of doing it than checking every possibility. Sorting the list didn't really show any evidence of puzzles that could be 'pruned' - areas that were the same but with increasing numbers of presents, say, so that you could reject the larger ones after the first failure.

Was kicking myself when it ran so quickly.

[–] CameronDev@programming.dev 2 points 1 week ago

Rust

Its not Christmas, but this one was a gift :D. Merry Christmas all, thanks for everyone who has contributed solutions!

Rest easy little advent bot, your work is done now.

spoiler

    struct Tree {
        w: u32,
        h: u32,
        presents: Vec<u32>,
    }

    fn is_solveable(tree: &Tree) -> bool {
        if tree.h * tree.w < tree.presents.iter().sum::<u32>() * 9 {
            return false;
        }
        true
    }

    #[test]
    fn test_y2025_day12_part1() {
        let input = include_str!("../../input/2025/day_12.txt");
        let parts = input.split("\n\n").collect::<Vec<_>>();

        let trees: Vec<Tree> = parts
            .last()
            .unwrap()
            .lines()
            .map(|line| {
                let parts: (&str, &str) = line.split_once(": ").unwrap();
                let [w, h] = parts
                    .0
                    .split("x")
                    .map(u32::from_str)
                    .map(Result::unwrap)
                    .collect::<Vec<_>>()[..]
                else {
                    unreachable!()
                };
                let num_presents = parts
                    .1
                    .split(" ")
                    .map(u32::from_str)
                    .map(Result::unwrap)
                    .collect::<Vec<_>>();
                Tree {
                    w,
                    h,
                    presents: num_presents,
                }
            })
            .collect();

        let mut solvable = 0;
        for tree in trees {
            if is_solveable(&tree) {
                solvable += 1;
            }
        }
        println!("solvable: {}", solvable);
    }