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

Day1   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
eloc 34
c 2
b 0
f 2
dl 0
loc 70
rs 10
wmc 15

6 Methods

Rating   Name   Duplication   Size   Complexity  
B calculateFirstBasementDirectionPosition() 0 23 7
A setDirections() 0 3 1
A calculateFloor() 0 11 4
A loadInput() 0 5 1
A solve() 0 6 1
A getDirections() 0 3 1
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