summaryrefslogtreecommitdiff
path: root/2018/aoc2018-d25.py
blob: 37367dfa1140e9f4b2718bf10f12b7dd30141748 (plain)
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
#advent of code 2018 
#day 25
#part 1

#at first seemed really easy, then it got a bit more complex
#but then again it seemed easy again
#it just required a bit more thought to put into
#could probably be bit more optimized, especially with Constellations variable
#which could be a simple counter instead of a list, but w/e

f = open("input.txt",'r');
Testing = False;
#Testing = True; 
if Testing:
	f.close();
	f = open("testinput.txt",'r');

class spacepoint:
	def __init__( self, coords ):
		self.Coords = coords;
		self.Adjacent = [];
		self.Visited = False;
	
	def manh_dist(self, OtherPoint): #calculate manhattan distance from self to OtherPoint
		m = 0;
		m += abs(self.Coords[0] - OtherPoint[0]);
		m += abs(self.Coords[1] - OtherPoint[1]);
		m += abs(self.Coords[2] - OtherPoint[2]);
		m += abs(self.Coords[3] - OtherPoint[3]);
		return m;
	#add all points from the grid that are within range to the "Adjacent" property 	
	def get_adjacent(self, grid):
		for g in grid:
			if self == grid[g]: continue;
			if (self.manh_dist(grid[g].Coords) <= 3):
				self.Adjacent.append(g);
	#recursive function(method) to make a list of all points that are in the same constellation
	#"Visited" property prevents an infinite loop 			
	def Find_Subset(self, grid, subset):
		self.Visited = True;
		subset.extend(self.Adjacent);
		for n in self.Adjacent:
			if grid[n].Visited: continue;
			subset = grid[n].Find_Subset(grid, subset);
		return subset;
	
	def __str__(self):
		return f'{self.Coords}';

#parse input into the program	
FixedPoints = {};
for l in f:
	l = "(" + l + ")";
	p = eval(l);
	FixedPoints.update({p:spacepoint(p)});
f.close();

#calculate neighbouring points for each point from input 
for p in FixedPoints:
	FixedPoints[p].get_adjacent(FixedPoints);

#find all constellations 
Constellations = [];
for p in FixedPoints:
	if FixedPoints[p].Visited: continue;
	Constellations.append(len(set(FixedPoints[p].Find_Subset(FixedPoints, [p]))));

part1 = len(Constellations);
print("part 1 = ", part1);