-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.1.php
135 lines (104 loc) · 2.48 KB
/
12.1.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
$input = <<<EOT
initial state: ##.#..########..##..#..##.....##..###.####.###.##.###...###.##..#.##...#.#.#...###..###.###.#.#
####. => #
##.#. => .
.##.# => .
..##. => .
..... => .
.#.#. => #
.###. => .
.#.## => .
#.#.# => .
.#... => #
#..#. => #
....# => .
###.. => .
##..# => #
#..## => #
..#.. => .
##### => .
.#### => #
#.##. => #
#.### => #
...#. => .
###.# => .
#.#.. => #
##... => #
...## => #
.#..# => .
#.... => .
#...# => .
.##.. => #
..### => .
##.## => .
..#.# => #
EOT;
function add_pots_needed_before(&$pots) {
$earliest_plant_index = array_search('#', array_column($pots, 'pot'));
$earliest_plant = $pots[$earliest_plant_index]['key'];
$earliest_pot = $pots[0]['key'];
if ($earliest_plant_index < 3) {
for ($i = 1; $i <= 3 - $earliest_plant; $i++) {
array_unshift($pots, [
'pot' => '.',
'key' => $earliest_pot - $i,
]);
}
}
}
function add_pots_needed_after(&$pots) {
$earliest_plant_index = array_search('#', array_column(array_reverse($pots), 'pot'));
$earliest_plant = $pots[$earliest_plant_index]['key'];
$latest_pot_index = max(array_keys($pots));
$latest_pot = $pots[$latest_pot_index]['key'];
if ($earliest_plant_index < 3) {
for ($i = 1; $i <= 3 - $earliest_plant_index; $i++) {
$pots[] = [
'pot' => '.',
'key' => $latest_pot + $i,
];
}
}
}
function add_needed_pots(&$pots) {
add_pots_needed_before($pots);
add_pots_needed_after($pots);
}
function process_generation($pots_arr, $combinations) {
add_needed_pots($pots_arr);
$new_pots = $pots_arr;
$i = 2;
$end = max(array_keys($pots_arr)) - 2;
while ($i <= $end) {
$these_5_arrays = array_slice($pots_arr, $i -2, 5);
$this_key = implode(array_column($these_5_arrays, 'pot'));
$new_pots[$i]['pot'] = $combinations[$this_key];
$i++;
}
return $new_pots;
}
preg_match('/initial state: (?<state>[#\.]+)/', $input, $matches);
$state = str_split($matches['state']);
preg_match_all('/(?<key>[#\.]+) => (?<value>#|\.)/', $input, $matches, PREG_SET_ORDER);
$combinations = [];
foreach ($matches as $match) {
$combinations[$match['key']] = $match['value'];
}
$pots_arr = [];
foreach ($state as $key => $pot) {
$pots_arr[] = [
'key' => $key,
'pot' => $pot,
];
}
for ($i = 0; $i < 20; $i++) {
$pots_arr = process_generation($pots_arr, $combinations);
}
$total_value = 0;
foreach ($pots_arr as $pot) {
if ($pot['pot'] === '#') {
$total_value += $pot['key'];
}
}
echo $total_value;