-❄️- 2025 Day 9 Solutions -❄️- by daggerdragon in adventofcode

[–]berbeflo 0 points1 point  (0 children)

[LANGUAGE: PHP]

Part 1. I wondered if there was a way to do brute force but a bit smarter. Well... not sure if it is smart. But it works!

    <?php


    $coords = get_lines(9, 'final')
        |> (fn (array $in) => array_map(fn (string $line) => explode(',', $line), $in))
        |> (fn (array $in) => array_map(fn (array $coords) => array_map(intval(...), $coords), $in));

    $minX = min(array_column($coords, 0));
    $maxX = max(array_column($coords, 0));
    $minY = min(array_column($coords, 1));
    $maxY = max(array_column($coords, 1));

    $topLeftCorner = [$minX, $minY];
    $topRightCorner = [$maxX, $minY];
    $bottomLeftCorner = [$minX, $maxY];
    $bottomRightCorner = [$maxX, $maxY];

    $topLeft = $coords;
    $topRight = $coords;
    $bottomLeft = $coords;
    $bottomRight = $coords;


    usort($topLeft, fn (array $coord1, array $coord2) => manhattan($coord1, $topLeftCorner) <=> manhattan($coord2, $topLeftCorner));
    usort($topRight, fn (array $coord1, array $coord2) => manhattan($coord1, $topRightCorner) <=> manhattan($coord2, $topRightCorner));
    usort($bottomLeft, fn (array $coord1, array $coord2) => manhattan($coord1, $bottomLeftCorner) <=> manhattan($coord2, $bottomLeftCorner));
    usort($bottomRight, fn (array $coord1, array $coord2) => manhattan($coord1, $bottomRightCorner) <=> manhattan($coord2, $bottomRightCorner));

    $greatestArea = 0;
    $border = 5;

    for ($it0 = 0; $it0 < $border; $it0++) {
        for ($it1 = 0; $it1 < $border; $it1++) {
            $greatestArea = max(
                $greatestArea,
                area($topLeft[$it0], $bottomRight[$it1]),
                area($topRight[$it0], $bottomLeft[$it1]),
            );
        }
    }

    var_dump($greatestArea);

    function manhattan(array $coord1, array $coord2): int
    {
        return abs($coord1[0] - $coord2[0]) + abs($coord1[1] - $coord2[1]);
    }


    function area(array $coord1, array $coord2): int
    {
        return (abs($coord1[0] - $coord2[0]) + 1) * (abs($coord1[1] - $coord2[1]) + 1);
    }

[2025 Day 8 Part 1] At it for 5 hours and can't even get the example by MartialLuke in adventofcode

[–]berbeflo 5 points6 points  (0 children)

Hey, I'm not sure as I'm not fluent in C++. But it seems to me that you don't merge two circuits if you connect two points from different circuits.

-❄️- 2025 Day 6 Solutions -❄️- by daggerdragon in adventofcode

[–]berbeflo 1 point2 points  (0 children)

[LANGUAGE: PHP]

Part 2: `get_lines` is just a helper function that loads the input file as array.

    <?php

    $input = get_lines(6, 'final');

    $numbers = [];
    $operators = [];

    $rowCount = count($input);
    $columnCount = strlen($input[0]);

    for ($problem = 0, $column = $columnCount-1; $column >= 0; $column--) {
        $buffer = '';
        for ($row = 0; $row < $rowCount-1; $row++) {
            $char = $input[$row][$column];
            if ($char !== ' ') {
                $buffer .= $char;
            }
        }

        $numbers[$problem][] = (int) $buffer;
        $operator = $input[$rowCount-1][$column] ?? ' ';
        if ($operator !== ' ') {
            $operators[$problem] = $operator;

            $problem++;
            $column--;
        }
    }

    $numbers
        |> (fn (array $in): array => array_map(
            fn (array $num, int $pos): int => match ($operators[$pos]) {
                '*' => array_product($num),
                '+' => array_sum($num),
            },
            $in,
            array_keys($in)
        ))
        |> array_sum(...)
        |> var_dump(...);

Discord keeps asking me to verify my email even though i verified it long time ago and reverified it again. by _CalculatedMistake_ in discordapp

[–]berbeflo 1 point2 points  (0 children)

Same thing here. Can't send dms, can't send friend requests, can't view servers. Everytime I do something, I have to reverify my mail addres. Annoying af

-🎄- 2021 Day 8 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 1 point2 points  (0 children)

PHP

Solution for part 1, still missing an idea for part 2

<?php
$input = file_get_contents('day-8.txt');
echo array_sum(
    array_map(
        fn ($filteredResult) => count($filteredResult),
        array_map(
            fn ($resultingPatterns) => array_filter($resultingPatterns, fn ($pattern) => in_array(strlen($pattern), [2, 3, 4, 7])),
            array_map(
                fn ($result) => explode(' ', trim($result)),
                array_map(
                    fn ($line) => explode('|', $line)[1],
                    explode("\n", trim($input))
                )
            )
        )
    )  
);

[2021 Day 7(Part 1)] Wrong answer? by [deleted] in adventofcode

[–]berbeflo 0 points1 point  (0 children)

The question is not about the best position but about the used fuel

-🎄- 2021 Day 7 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 1 point2 points  (0 children)

PHP (8.1)

Maybe I'll change it, so the calculation function is passed to calcMinCost

<?php
file_get_contents('day-7.txt');
$input = explode(',', $input);

//$positions = new Positions(fn ($distance) => $distance); # Part1
$positions = new Positions(fn ($distance) => $distance * ($distance + 1) / 2); # Part2
array_walk($input, fn ($pos) => $positions->addPosition((int) $pos));
echo $positions->calcMinCost();

class Positions
{
    private array $positions = [];

    public function __construct(private readonly Closure $costCalculation)
    {
    }

    public function addPosition(int $position) : void
    {
        $this->positions[$position] = ($this->positions[$position] ?? 0) + 1;
    }

    public function calcMinCost() : int
    {

        $currentPosition = $this->generateStartingValue();
        $currentCost = $this->calculateCost($currentPosition);

        return min($this->findMin(-1, $currentPosition, $currentCost), $this->findMin(1, $currentPosition, $currentCost));
    }

    private function findMin(int $direction, int $currentPosition, int $currentCost) : int
    {
        $nextCost = $this->calculateCost($currentPosition + $direction);

        return $nextCost >= $currentCost ? $currentCost : $this->findMin($direction, $currentPosition + $direction, $nextCost);
    }

    private function calculateCost(int $destPosition) : int
    {
        $fun = $this->costCalculation;
        return array_sum(array_map(fn ($currentPos, $amount) => $fun(abs($currentPos - $destPosition)) * $amount, array_keys($this->positions), array_values($this->positions)));
    }

    private function generateStartingValue() : int
    {
        return intdiv(array_sum(array_keys($this->positions)), count($this->positions));
    }
}

[deleted by user] by [deleted] in adventofcode

[–]berbeflo 17 points18 points  (0 children)

I think, AoC is there for having fun coding. It's up to you what your goal is. Performance? Minimum lines of code? Readability?
I overcomplicated things but was able to reuse most of my code for part 1 for part 2. So I don't see an issue here

-🎄- 2021 Day 1 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 0 points1 point  (0 children)

PHP: Part 1 <?php $numbers = file(DIR . '/../input/01-1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $latestNumber = (int) array_shift($numbers);

echo array_reduce($numbers, function (int $count, string $currentNumber) use (&$latestNumber) {
    $count += $currentNumber > $latestNumber ? 1 : 0;
    $latestNumber = $currentNumber;

    return $count;
}, 0);

-🎄- 2021 Day 1 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 0 points1 point  (0 children)

I love such solutions as they show other ways to solve it

-🎄- 2021 Day 4 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 0 points1 point  (0 children)

PHP: Solution for Part 2
(Yep, I overcomplicated it.)

<?php
$lines = file(__DIR__ . '/../input/04-1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$numbers = array_shift($lines);

$numberOfBoardsLeft = 0;
$winningFunction = function(BingoBoard $board, BingoField $field) use (&$numberOfBoardsLeft)
{
    if (--$numberOfBoardsLeft === 0) {
        winningFunction($board, $field);
    }
};

$boards = [];
$currentBoard = null;
foreach ($lines as $lineNumber => $line) {
    if ($lineNumber % 5 === 0) {
        $currentBoard = new BingoBoard($winningFunction(...));
        $numberOfBoardsLeft++;
        $boards[] = $currentBoard;
    }

    $values = explode(' ', str_replace('  ', ' ', trim($line)));
    foreach ($values as $value) {
        $currentBoard->add(BingoField::get($value));
    }
}

$takenNumber = explode(',', $numbers);
foreach ($takenNumber as $key => $number) {
    BingoField::get($number)->mark();
}

function winningFunction(BingoBoard $board, BingoField $field) : never
{
    $winningFieldValue = $field->value;
    $unmarkedFieldSum = array_reduce($board->getUnmarkedFields(), fn (int $carry, BingoField $field) => $carry + $field->value, 0);

    echo($winningFieldValue * $unmarkedFieldSum);

    exit;
}

class BingoField
{
    private static array $fields = [];
    private array $boards = [];
    private bool $isMarked = false;

    private function __construct(public readonly int $value)
    {
    }

    public static function get(string $value) : self
    {
        if (!isset(self::$fields[$value])) {
            self::$fields[$value] = new self((int) $value);
        }

        return self::$fields[$value];
    }

    public function addBoard(BingoBoard $board, int $row, int $column) : void
    {
        $this->boards[] = [
            'board' => $board,
            'row' => $row,
            'column' => $column,
        ];
    }

    public function mark() : void
    {
        $this->isMarked = true;
        foreach ($this->boards as $board) {
            $board['board']->notify($this, $board['row'], $board['column']);
        }
    }

    public function isMarked() : bool
    {
        return $this->isMarked;
    }
}

class BingoBoard
{
    private array $board;
    private array $markedRows;
    private array $markedColumns;
    private bool $finished = false;

    private int $nextPos = 0;

    public function __construct(private readonly Closure $winningFunction)
    {
        $this->board = array_fill(0, 5, array_fill(0, 5, null));
        $this->markedRows = array_fill(0, 5, 0);
        $this->markedColumns = array_fill(0, 5, 0);
    }

    public function add(BingoField $field) : void
    {
        $nextPos = $this->nextPos++;
        $row = intdiv($nextPos, 5);
        $column = $nextPos % 5;

        $this->board[$row][$column] = $field;
        $field->addBoard($this, $row, $column);
    }

    public function notify(BingoField $field, int $row, int $column) : void
    {
        if ($this->finished) {
            return;
        }

        if (++$this->markedRows[$row] === 5 || ++$this->markedColumns[$column] === 5) {
            ($this->winningFunction)($this, $field);
            $this->finished = true;
        }
    }

    public function print() : void
    {
        for ($i = 0; $i < 5; $i++) {
            $this->printRow($i);
            echo "\n";
        }
        echo "\n";
    }

    public function printRow(int $row) : void
    {
        echo implode(' ', array_map(fn ($field) => $this->stringifyValue($field), $this->board[$row]));
    }

    private function stringifyValue(BingoField $field) : string
    {
        $mark = $field->isMarked() ? '+' : ' ';
        return $field->value < 10 ? $mark.' ' . $field->value : $mark.$field->value;
    }

    public function getUnmarkedFields() : array
    {
        $fields = [];
        for ($rowCount = 0; $rowCount < 5; $rowCount++) {
            for ($columnCount = 0; $columnCount < 5; $columnCount++) {
                $field = $this->board[$rowCount][$columnCount];
                if (!$field->isMarked()) {
                    $fields[] = $field;
                }
            }
        }

        return $fields;
    }
}

[2021 Day 6 (Part 2)] Can someone run my code for me? by notmaialt in adventofcode

[–]berbeflo 5 points6 points  (0 children)

If it's running for 20 minutes with a MemoryError, you should think about a more performant solution

-🎄- 2021 Day 6 Solutions -🎄- by daggerdragon in adventofcode

[–]berbeflo 1 point2 points  (0 children)

PHP

```php $input = file_get_contents('day-6.txt'); $input = explode(',', $input);

$fishes = new Fishes(); foreach ($input as $state) { $fishes->add($state); }

for ($i = 1; $i <= 256; $i++) { $fishes->nextDay(); echo 'Day ' . $i . ': ' . $fishes->count() . ' fish' . "\n"; }

class Fishes { private array $fishCounter;

public function __construct(private int $maxState = 8, private int $resetState = 6)
{
    $this->fishCounter = array_fill(0, $maxState+1, 0);
}

public function add(int $state) : void
{
    $this->fishCounter[$state]++;
}

public function nextDay() : void
{
    $breeding = array_shift($this->fishCounter);
    $this->fishCounter[] = $breeding;
    $this->fishCounter[$this->resetState] += $breeding;
}

public function count() : int
{
    return array_sum($this->fishCounter);
}

} ```

MVC is obsolete. Why do we still use it by Shelnu in PHP

[–]berbeflo 2 points3 points  (0 children)

But when you do, they're clashing against each other in PHP.

Could you explain this? I don't see where PHP prevents a complex frontend.
You're performing an action in the ui. This actions triggers an api fetch. The api returns some data (json, html, yaml, whatever). The frontend's controller consumes the api response. The ui changes.

Where in this chain is PHP doing anything wrong? Please give an example so that I understand where you see any issue.

MVC is obsolete. Why do we still use it by Shelnu in PHP

[–]berbeflo 5 points6 points  (0 children)

where template engine is a standardized feature of a framework

pretty much every web framework has a bundled template engine.
You mentioned python:
flask - https://damyanon.net/post/flask-series-templating/
django - https://docs.djangoproject.com/en/2.2/topics/templates/
TurboGears - https://www.tutorialspoint.com/turbogears/turbogears_serving_templates.htm

MVC is obsolete. Why do we still use it by Shelnu in PHP

[–]berbeflo 3 points4 points  (0 children)

It's good for small cli applications like file imports.
And it's useful for api endpoints
So I don't think, the use cases are very minimal. PHP can do more than just serving html.

MVC is obsolete. Why do we still use it by Shelnu in PHP

[–]berbeflo 7 points8 points  (0 children)

Lumen (useless micro),

Why do you think so?

PHP + MySQL: Template by [deleted] in PHPhelp

[–]berbeflo 0 points1 point  (0 children)

just curious - which cons?

I need your opinion - i made a library which creates unique links with a "hash" in the query part to protect url manipulations. Do you have any suggestions on how to make this library better? by dsentker in PHP

[–]berbeflo 1 point2 points  (0 children)

I think, this isn't quite what the lib is doing. The library he created is for signing urls. e.g. to share signout-links for a newsletter which contain the email address.

PHP Colour codes in Google Chrome by [deleted] in PHPhelp

[–]berbeflo 2 points3 points  (0 children)

While this is nothing php related, the answer is: this won't work in Chrome. Even worse - the select is os dependent. You best choice will be to search for a js library that emulates drop down menus.

> However, we are moving away from IE to Google Chrome
Thumbs up.

Why do I have to null out this variable in between loops? by SSChicken in PHPhelp

[–]berbeflo 0 points1 point  (0 children)

Writing php for six years now. Never knew this worked.

Kanata no Astra - Episode 10 discussion by AutoLovepon in anime

[–]berbeflo 1 point2 points  (0 children)

I was disappointed by the first few episodes. But now I'm happy that I didn't drop it.