-
Notifications
You must be signed in to change notification settings - Fork 0
/
polymer.php
executable file
·51 lines (39 loc) · 1.08 KB
/
polymer.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
#!/usr/bin/php
<?php
function remove(&$string, $pos, $length) {
$string = substr($string, 0, $pos) . substr($string, $pos+$length);
}
function polymer_strength($input) {
do {
$changed = false;
for($i = 0; $i < 26; ++$i) {
$smallLetter = chr(97 + $i);
$largeLetter = chr(65 + $i);
$rem = $smallLetter.$largeLetter;
$pos = strpos($input, $rem);
if($pos === FALSE) {
$rem = $largeLetter.$smallLetter;
$pos = strpos($input, $rem);
}
if($pos !== FALSE) {
remove($input, $pos, 2);
$changed = TRUE;
// echo "--> removed $rem at pos $pos\n";
break;
}
}
} while($changed);
return strlen($input);
}
$input = trim(fgets(STDIN));
echo "part1: " . polymer_strength($input) . "\n";
$best = strlen($input);
for($i = 0; $i < 26; ++$i) {
$smallLetter = chr(97 + $i);
$largeLetter = chr(65 + $i);
$new_input = preg_replace("/[$smallLetter$largeLetter]/",'',$input);
$new_strength = polymer_strength($new_input);
echo "--> part2: $smallLetter$largeLetter: $new_strength\n";
if($new_strength < $best) $best = $new_strength;
}
echo "part2: $best\n";