Passed
Push — master ( ea64ab...0482fa )
by Daan
01:28
created

Day1::calculateFirstBasementDirectionPosition()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 15
c 1
b 0
f 1
nc 7
nop 1
dl 0
loc 23
rs 8.8333
1
<?php
2
3
namespace DaanMooij\AdventOfCode\Year2015;
4
5
use DaanMooij\AdventOfCode\Day;
6
7
class Day1 implements Day
8
{
9
    const FLOOR_UP = '(';
10
    const FLOOR_DOWN = ')';
11
    const STARTING_FLOOR = 0;
12
13
    private array $directions = [];
14
15
    public function loadInput(): void
16
    {
17
        $filepath = __DIR__ . "/input/day-1.txt";
18
19
        $this->directions = str_split(file_get_contents($filepath));
20
    }
21
22
    public function solve()
23
    {
24
        printf("The resulting floor is: %s\n", $this->calculateFloor(self::STARTING_FLOOR));
25
        printf(
26
            "The first direction position that causus Santa to go in the basement is: %s\n",
27
            $this->calculateFirstBasementDirectionPosition(self::STARTING_FLOOR)
28
        );
29
    }
30
31
    public function calculateFloor(int $floor = self::STARTING_FLOOR): int
32
    {
33
        foreach ($this->directions as $direction) {
34
            if ($direction === self::FLOOR_UP) {
35
                $floor++;
36
            } elseif ($direction === self::FLOOR_DOWN) {
37
                $floor--;
38
            }
39
        }
40
41
        return $floor;
42
    }
43
44
    public function calculateFirstBasementDirectionPosition(int $floor = self::STARTING_FLOOR): int
45
    {
46
        if ($floor < 0) return 0;
47
48
        $basementPostion = 1;
49
        $inBasement = false;
50
        while(!$inBasement) {
51
            foreach ($this->directions as $position => $direction) {
52
                if ($direction === self::FLOOR_UP) {
53
                    $floor++;
54
                } elseif ($direction === self::FLOOR_DOWN) {
55
                    if ($floor === 0) {
56
                        $basementPostion = $position + 1;
57
                        $inBasement = true;
58
                        break;
59
                    }
60
                    $floor--;
61
                }
62
                $basementPostion = $position + 1;
63
            }
64
        }
65
66
        return $basementPostion;
67
    }
68
69
    public function setDirections(array $directions): void
70
    {
71
        $this->directions = $directions;
72
    }
73
74
    public function getDirections(): array
75
    {
76
        return $this->directions;
77
    }
78
}
79