-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.php
82 lines (67 loc) · 1.41 KB
/
day2.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
<?php
print "Part 1 = " . part1() . "\n";
print "Part 2 = " . part2() . "\n";
function part1()
{
$lines = explode("\n", file_get_contents('day2-input.txt'));
$twos = getExactCounts($lines, 2);
$threes = getExactCounts($lines, 3);
print "Twos = $twos, threes = $threes\n";
return $twos * $threes;
}
function getExactCounts($lines, $target)
{
$matches = 0;
foreach ($lines as $line) {
if (doesLineHaveCount($line, $target)) {
$matches++;
}
}
return $matches;
}
function doesLineHaveCount($line, $target)
{
$chars = [];
foreach (str_split($line) as $char) {
$chars[$char]++;
}
foreach ($chars as $count) {
if ($count === $target) {
return true;
}
}
return false;
}
function part2()
{
$lines = explode("\n", file_get_contents('day2-input.txt'));
$lineCount = count($lines);
for ($first = 0; $first < $lineCount - 1; $first++) {
for ($second = $first + 1; $second < $lineCount; $second++) {
$diff = diffChars($lines[$first], $lines[$second]);
if ($diff === 1) {
return findCommon($lines[$first], $lines[$second]);
}
}
}
}
function diffChars($line1, $line2)
{
$diffs = 0;
for ($i = 0; $i < strlen($line1); $i++) {
if ($line1[$i] !== $line2[$i]) {
$diffs++;
}
}
return $diffs;
}
function findCommon($line1, $line2)
{
$result = '';
for ($i = 0; $i < strlen($line1); $i++) {
if ($line1[$i] === $line2[$i]) {
$result .= $line1[$i];
}
}
return $result;
}