-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspelled-out.php
executable file
·67 lines (58 loc) · 1.19 KB
/
spelled-out.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
#!/usr/bin/php
<?php
function extract_first_last_digit($input) {
$digits = [];
$length = strlen($input);
for($i = 0; $i < $length; ++$i) {
if((ord($input[$i]) >= 48) && (ord($input[$i] <= 57))) {
$digits[] = $input[$i];
}
}
$count = count($digits);
if($count === 0) return "";
return $digits[0] . $digits[$count-1];
}
function convert_spelled_digits($input) {
$output = "";
$digits = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
];
$length = strlen($input);
$pos = 0;
while($pos < $length) {
foreach($digits as $digit => $word) {
$wlen = strlen($word);
if(substr($input, $pos, $wlen) === $word) {
$output .= $digit;
$pos += 1; // $wlen;
continue 2;
}
}
$output .= $input[$pos];
$pos += 1;
}
return $output;
}
$part1 = 0;
$part2 = 0;
while(true) {
$line = fgets(STDIN);
if($line === FALSE) break;
$line = trim($line);
if($line === "") continue;
$digits1 = extract_first_last_digit($line);
if($digits1 !== "") $part1 += $digits1;
$digits2 = extract_first_last_digit(convert_spelled_digits($line));
if($digits2 !== "") $part2 += $digits2;
}
echo "Part1: ", $part1, "\n";
echo "Part2: ", $part2, "\n";