-
Notifications
You must be signed in to change notification settings - Fork 0
/
fold.php
executable file
·85 lines (73 loc) · 1.62 KB
/
fold.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
#!/usr/bin/php
<?php
class Dot {
public $x;
public $y;
public function __construct($x, $y) {
$this->x = (int)$x;
$this->y = (int)$y;
}
public function fold($axis, $position) {
if($axis === 'x') {
$axisPos =& $this->x;
} else {
$axisPos =& $this->y;
}
if($axisPos > $position) {
$axisPos = $position - ($axisPos - $position);
}
}
public function __toString() {
return "{$this->x}:{$this->y}";
}
}
$dots = [];
while(($line = fgets(STDIN)) !== false) {
$line = trim($line);
if($line === "") break;
$dots[] = new Dot(...explode(',', $line));
}
$folds = [];
while(($line = fgets(STDIN)) !== false) {
$line = trim($line);
if(substr($line, 0, 11) !== "fold along ") {
fprintf(STDERR, "Invalid input\n");
exit(1);
}
$line = substr($line, 11);
$line = explode('=', $line);
$folds[] = [
strtolower($line[0]),
(int)$line[1]
];
}
echo "Before folding: ", count($dots), " dots\n";
foreach($folds as [$axis, $value]) {
foreach($dots as &$dot) {
$dot->fold($axis, $value);
}
$dots = array_unique($dots, SORT_STRING);
echo "After folding on {$axis}={$value}: ", count($dots), " dots\n";
}
$maxX = $maxY = 0;
$minX = $minY = PHP_INT_MAX;
foreach($dots as $dot) {
if($dot->x < $minX) $minX = $dot->x;
if($dot->x > $maxX) $maxX = $dot->x;
if($dot->y < $minY) $minY = $dot->y;
if($dot->y > $maxY) $maxY = $dot->y;
}
$width = ($maxX - $minX + 1);
$height = ($maxY - $minY + 1);
$image = [];
for($y = 0; $y < $height; ++$y) {
$image[$y] = str_repeat('.', $width);
}
foreach($dots as $dot) {
$x = $dot->x - $minX;
$y = $dot->y - $minY;
$image[$y][$x] = '#';
}
foreach($image as $row) {
echo $row, "\n";
}