# Advent of Code 2021 | Day 5 | Solutions in Python3

Here are the solutions for today’s Advent of Code 2021, Day 5 answers in Python3.

Contents

## Logic

• Logic for part 1 and part 2 is very similar.
• I take the help of the `get_points` function to get a list of points between p1 and p2 (supplied as input). By initializing the x and y values to x1 and y1, and iterating over all the points in the middle to get to x2, y2.
• The direction of p1 to p2 can be either towards top-right or bottom-left. To consider both the cases together, I used a simple if condition to check x with x2 and y with y2.
• Since there can be repetitions, I have used a `set()` instead of a `list`. We return the points as a list though.

## Part 1

```from collections import defaultdict

def get_input():
data = []
with open("input.txt") as f:
return data

def get_points(p1, p2):
points = set()
x1, x2 = p1, p2
y1, y2 = p1, p2

if x1 != x2 and y1 != y2:
return []

x, y = x1, y1
while (not x == x2) or (not y == y2):
if x < x2:
x += 1
elif x > x2:
x -= 1

if y < y2:
y += 1
elif y > y2:
y -= 1
return list(points)

def clean_point(p):
return list(map(int, p.split(",")))

def solve(data):

d = defaultdict(int)
for line in data:
p1, p2 = line.split(" -> ")
p1, p2 = clean_point(p1), clean_point(p2)
for point in get_points(p1, p2):
d[tuple(point)] += 1

return len([d[point] for point in d if d[point] >= 2])

print(solve(get_input()))
```

## Part 2

The only change is the removal of the `if x1 != x2 and y1 != y2: return []` condition, since we can have diagonal lines along with horizontal and vertical ones.

```from collections import defaultdict

def get_input():
data = []
with open("input.txt") as f:
return data

def get_points(p1, p2):
points = set()
x1, x2 = p1, p2
y1, y2 = p1, p2

x, y = x1, y1
while (not x == x2) or (not y == y2):
if x < x2:
x += 1
elif x > x2:
x -= 1

if y < y2:
y += 1
elif y > y2:
y -= 1
return list(points)

def clean_point(p):
return list(map(int, p.split(",")))

def solve(data):

d = defaultdict(int)
for line in data:
p1, p2 = line.split(" -> ")
p1, p2 = clean_point(p1), clean_point(p2)
for point in get_points(p1, p2):
d[tuple(point)] += 1

return len([d[point] for point in d if d[point] >= 2])

print(solve(get_input()))
```
##### Tanishq Chaudhary Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

### Recommended Posts

##### Gas Station | InterviewBit | Solution Explained

June 13, 2022

##### Seats | InterviewBit | Solution Explained

June 13, 2022

##### Meeting Rooms | InterviewBit | Solution Explained

June 13, 2022

This site uses Akismet to reduce spam. Learn how your comment data is processed.