-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
75 lines (57 loc) · 2.82 KB
/
main.py
File metadata and controls
75 lines (57 loc) · 2.82 KB
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
import time
def get_expansion_map(curr_map):
expansions = {}
for i in range(len(curr_map)):
expansions[i] = expansions.get(i - 1, 0)
if "#" not in curr_map[i]:
expansions[i] += 1
return expansions
def main(input_file, stage=1):
with open(input_file) as file:
galaxy_map = file.readlines()
galaxy_map = [[*line.strip()] for line in galaxy_map]
galaxy_map_transposed = list(zip(*galaxy_map))
# expand galaxy map
# expansion factor reduced by one, as if one row is empty only one row will be added, not two
expansion_factor = 1
if stage == 2:
expansion_factor = 10**6-1
# original code from stage 1, "bruteforce", just adding the rows directly
#galaxy_map = [row for line in galaxy_map for row in (line,) * (expansion_factor if line.count("#") == 0 else 1)]
#galaxy_map = list(zip(*galaxy_map))
#galaxy_map = [col for line in galaxy_map for col in (line,) * (expansion_factor if line.count("#") == 0 else 1)]
#galaxy_map = list(zip(*galaxy_map))
# find all the galaxies
galaxies = set()
for i1, g1 in enumerate(galaxy_map):
if "#" not in g1:
continue
# if I would not have split the input map into lists, this could also be done with regex
for i2 in range(0, len(galaxy_map[i1])):
if g1[i2] == "#":
galaxies.add((i1, i2))
# sort by y coordinate, to allow minimal loop time later on
galaxies = list(sorted(galaxies, key=lambda x: x[0]))
expansions_y = get_expansion_map(galaxy_map)
expansions_x = get_expansion_map(galaxy_map_transposed)
distance = 0
# minimal galaxy pair set: (len(galaxies)*(len(galaxies)-1))/2
for i in range(len(galaxies)):
for j in range(i+1, len(galaxies)):
first_galaxy = galaxies[i]
second_galaxy = galaxies[j]
start_ = first_galaxy[0] + (expansions_y[first_galaxy[0]] * expansion_factor)
end_ = first_galaxy[1] + (expansion_factor * expansions_x[first_galaxy[1]])
start2_ = second_galaxy[0] + (expansions_y[second_galaxy[0]] * expansion_factor)
end2_ = second_galaxy[1] + (expansion_factor * expansions_x[second_galaxy[1]])
distance += abs(start_ - start2_) + abs(end_ - end2_)
print(distance)
if __name__ == "__main__":
use_example = False
file_name = "example" if use_example else "input"
start_time = time.time()
main(file_name, 1)
print(f"Stage 1 time: {time.time()-start_time:.10f}")
start_time = time.time()
main(file_name, 2)
print(f"Stage 2 time: {time.time()-start_time:.10f}")