1
+ <?php
2
+
3
+ $ lines = [];
4
+
5
+ //read input and format it into the set of numbers and the bingo boards
6
+ $ input = fopen ("input.txt " , "r " );
7
+ while (($ input_line = fgets ($ input )) !== false ) {
8
+ $ lines [] = trim ($ input_line );
9
+ }
10
+ fclose ($ input );
11
+
12
+
13
+ $ line_map = []; //multidimensional array with every point where lines are detected (first key is y, second x, as y is vertical)
14
+ foreach ($ lines as $ line ) {
15
+ $ line = str_replace (' -> ' , ', ' , $ line ); //replace the arrow with another comma so we can explode into 4 coordinates easily
16
+ list ($ x1 , $ y1 , $ x2 , $ y2 ) = explode (', ' , $ line ); //first two are start, second two are end
17
+
18
+ //only consider horizontal or vertical lines (x1 == x2 or y1 == y2)
19
+ if ($ x1 == $ x2 || $ y1 == $ y2 ) {
20
+
21
+ if ($ y1 == $ y2 ) { //if y stays the same, mark the range of all x
22
+ foreach (range ($ x1 , $ x2 ) as $ x_coordinate ) {
23
+ if (!isset ($ line_map [$ y1 ])){
24
+ $ line_map [$ y1 ] = []; //check if we already have an x row for this y coordinate
25
+ }
26
+ if (!isset ($ line_map [$ y1 ][$ x_coordinate ])){
27
+ $ line_map [$ y1 ][$ x_coordinate ] = 1 ; //if no entry for this y/x position existed, initalise with 1 as it's the first occurrence
28
+ }
29
+ else {
30
+ $ line_map [$ y1 ][$ x_coordinate ]++; //otherwise increase the count
31
+ }
32
+ }
33
+ }
34
+ else { //if x stays the same, mark the range of all y
35
+ foreach (range ($ y1 , $ y2 ) as $ y_coordinate ) {
36
+ if (!isset ($ line_map [$ y_coordinate ])){
37
+ $ line_map [$ y_coordinate ] = []; //check if we already have an x row for this y coordinate
38
+ }
39
+ if (!isset ($ line_map [$ y_coordinate ][$ x1 ])){
40
+ $ line_map [$ y_coordinate ][$ x1 ] = 1 ; //if no entry for this y/x position existed, initalise with 1 as it's the first occurrence
41
+ }
42
+ else {
43
+ $ line_map [$ y_coordinate ][$ x1 ]++; //otherwise increase the count
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ //now we need to find every value in the array that is higher than 1
51
+ $ line_count = 0 ;
52
+ foreach ($ line_map as $ row ) {
53
+ foreach ($ row as $ single_pos ) {
54
+ if ($ single_pos > 1 ) {
55
+ $ line_count ++; //if a value is greater than one increase the counter
56
+ }
57
+ }
58
+ }
59
+ echo $ line_count . PHP_EOL ;
0 commit comments