class FloorMap: def __init__(self, size_x, size_y): self.board = [] for _ in range(size_y+1): self.board.append([0]*(size_x+1)) def add_line(self, start_pos, end_pos): if start_pos[0] == end_pos[0]: # Vertical line: X stays constant, Y changes if start_pos[1] > end_pos[1]: start_pos, end_pos = end_pos, start_pos for i in range(start_pos[1], end_pos[1]+1): self.board[i][start_pos[0]] = self.board[i][start_pos[0]] + 1 elif start_pos[1] == end_pos[1]: # Horizontal line: Y stays constant, X changes if start_pos[0] > end_pos[0]: start_pos, end_pos = end_pos, start_pos for i in range(start_pos[0], end_pos[0]+1): self.board[start_pos[1]][i] = self.board[start_pos[1]][i] + 1 else: # Diagonal line: X and Y both change # These are only ever 45° angles, so each changes by 1 per iteration. if start_pos[0] > end_pos[0]: start_pos, end_pos = end_pos, start_pos i, j = start_pos end_i, end_j = end_pos[0], end_pos[1] # I've arranged this so X always increases. Y can either increase or decrease. # I don't like that so much repeats. # What I WANT to do here is be able to set a toggle variable so that # if Y decreases, the second condition flips from <= to >=, # and then j += dir, which is either 1 or -1. # But I can't find a way to do it without eval() bullshit. if j <= end_j: # there should be no cases where they're equal, but... while i <= end_i and j <= end_j: self.board[j][i] = self.board[j][i] + 1 i += 1 j += 1 else: while i <= end_i and j >= end_j: self.board[j][i] = self.board[j][i] + 1 i += 1 j -= 1 def count_inters(self): return sum([len([el for el in line if el >= 2]) for line in self.board]) def __repr__(self): outstr = "" for line_num in range(10): outstr += f"{' '.join(str(self.board[line_num]))}" return outstr def __str__(self): outstr = "" for line_num in range(10): outstr += f"{' '.join(str(self.board[line_num]))}" return outstr def main(): with open("aoc5-1.txt", "r") as file: lines = [line.strip() for line in file.readlines()] # Each line is a pair of x,y coordinates...es separated by " -> " lines = [[list(map(int, el.split(","))) for el in line.split(" -> ")] for line in lines] # god, this feels goofy, but it works size_x = max([max(line[0][0], line[1][0]) for line in lines]) size_y = max([max(line[0][1], line[1][1]) for line in lines]) board_map = FloorMap(size_x, size_y) for line in lines: board_map.add_line(*line) print(board_map.count_inters()) if __name__ == "__main__": main()