Passed
Push — master ( bdce49...6393b8 )
by Daan
01:21
created

Day1::getFrequencyReachedTwice()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 1
dl 0
loc 19
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace DaanMooij\AdventOfCode\Year2018\Day1;
4
5
use DaanMooij\AdventOfCode\Day;
6
use Exception;
7
8
class Day1 implements Day
9
{
10
    /**
11
     * @var array<int>
12
     */
13
    private array $changes = [];
14
15
    /**
16
     * @return void
17
     */
18
    public function loadInput(): void
19
    {
20
        $filepath = __DIR__ . '/input.txt';
21
        $input = fopen($filepath, "r");
22
23
        if (!is_resource($input)) {
24
            throw new Exception("Could not open input file: {$filepath}");
25
        }
26
27
        while (!feof($input)) {
28
            $this->changes[] = intval(fgets($input));
29
        }
30
        fclose($input);
31
    }
32
33
    /**
34
     * @return void
35
     */
36
    public function solve(): void
37
    {
38
        printf("The resulting frequency is: %s\n", $this->calculateFrequency());
39
        printf("The first frequency that's reached twice is: %s\n", $this->getFrequencyReachedTwice());
40
    }
41
42
    /**
43
     * @param array<int> $changes
44
     * @return void
45
     */
46
    public function setChanges(array $changes): void
47
    {
48
        $this->changes = $changes;
49
    }
50
51
    /**
52
     * @return array<int>
53
     */
54
    public function getChanges(): array
55
    {
56
        return $this->changes;
57
    }
58
59
    /**
60
     * @param int $frequency -> The starting frequency
61
     * @return int
62
     */
63
    public function calculateFrequency(int $frequency = 0): int
64
    {
65
        foreach ($this->changes as $change) {
66
            $frequency += $change;
67
        }
68
69
        return $frequency;
70
    }
71
72
    /**
73
     * @param int $frequency -> The starting frequency
74
     * @return int
75
     */
76
    public function getFrequencyReachedTwice(int $frequency = 0): int
77
    {
78
        $memory = [$frequency => 1];
79
80
        $found = false;
81
        while (!$found) {
82
            foreach ($this->changes as $change) {
83
                $frequency += $change;
84
85
                if (isset($memory[$frequency])) {
86
                    $found = true;
87
                    break;
88
                }
89
90
                $memory[$frequency] = 1;
91
            }
92
        }
93
94
        return $frequency;
95
    }
96
}
97