-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.php
100 lines (81 loc) · 2.84 KB
/
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
<?php
// Test Data:
// $input = ["1abc2", "pqr3stu8vwx", "a1b2c3d4e5f", "treb7uchet"];
$input = file("inputs/1.txt");
$calibrationValuesSum = 0;
for($line = 0; $line < count($input); $line++){
// Find first digit
$firstDigit = 0;
for($charIndex = 0; $charIndex < strlen($input[$line]); $charIndex++){
if(is_numeric($input[$line][$charIndex])){
$firstDigit = $input[$line][$charIndex];
break;
}
}
// Find last digit
$lastDigit = 0;
for($charIndex = strlen($input[$line]) - 1; $charIndex >= 0; $charIndex--){
if(is_numeric($input[$line][$charIndex])){
$lastDigit = $input[$line][$charIndex];
break;
}
}
$digit = $firstDigit * 10 + $lastDigit;
$calibrationValuesSum += $digit;
}
echo "Calibration values sum (Part a): " . $calibrationValuesSum . "\n";
// Test Data:
// $input = [
// "two1nine",
// "eightwothree",
// "abcone2threexyz",
// "xtwone3four",
// "4nineeightseven2",
// "zoneight234",
// "7pqrstsixteen",
// ];
$calibrationValuesSum = 0;
for($line = 0; $line < count($input); $line++){
// Find first digit
$firstDigit = 0;
for($charIndex = 0; $charIndex < strlen($input[$line]); $charIndex++){
if(is_numeric($input[$line][$charIndex])){
$firstDigit = $input[$line][$charIndex];
break;
}else{
$digit = isNumberWord($input[$line], $charIndex);
if($digit != 0){
$firstDigit = $digit;
break;
}
}
}
// Find last digit
$lastDigit = 0;
for($charIndex = strlen($input[$line]) - 1; $charIndex >= 0; $charIndex--){
if(is_numeric($input[$line][$charIndex])){
$lastDigit = $input[$line][$charIndex];
break;
}else{
$digit = isNumberWord($input[$line], $charIndex);
if($digit != 0){
$lastDigit = $digit;
break;
}
}
}
$digit = $firstDigit * 10 + $lastDigit;
$calibrationValuesSum += $digit;
}
echo "Calibration values sum (Part b): " . $calibrationValuesSum . "\n";
function isNumberWord($string, $position) : int {
$numberWords = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
$word = substr($string, $position, 5);
for($numberWord = 0; $numberWord < count($numberWords); $numberWord++){
if(str_starts_with($word, $numberWords[$numberWord])){
return $numberWord + 1;
}
}
return 0;
}
?>