view the Advent of Code 2021 Day 2 challenge
# Setup - load any packages
import pandas as pd
# load data into Pandas DataFrame
data_raw = pd.read_csv('day2_data.txt',delimiter=' ', index_col=False, header=None)
# Add column names
data_raw.columns =['direction', 'distance']
# Check the data types of the columns
print(data_raw.dtypes)
# set the direction column as the index
data_raw=data_raw.set_index('direction')
# View the first few rows of the data
data_raw.head()
direction object distance int64 dtype: object
distance | |
---|---|
direction | |
forward | 2 |
down | 9 |
up | 6 |
forward | 1 |
down | 5 |
# copy the raw data for use in part 1
part1=data_raw.copy()
# variables to store the distance and depth
distance=0
depth=0
# Group by the direction to get the overal distances
part1=part1.groupby(['direction']).sum()
# view the group by results
print(part1.head())
# set the distance
distance=part1.loc['forward'][0]
# set the depth
depth = depth + part1.loc['down'][0] - part1.loc['up'][0]
print(f'distance = {distance} depth = {depth}')
position = distance * depth
print (f'answer = {position}')
distance direction down 1991 forward 2010 up 961 distance = 2010 depth = 1030 answer = 2070300
# copy the raw data for use in part 2
part2=data_raw.copy()
# Drop the index
part2.reset_index(drop=False, inplace=True)
# declare variables to store the distance, depth and aim
p2_dist=0
p2_depth=0
p2_aim=0
# itterate through each row of directions
for index, row in part2.iterrows():
if (row['direction']=='forward'):
#increase distance
p2_dist += row['distance']
# check aim of submarine
if p2_aim!= 0:
# not aiming forward so increase/decrease depth by aim
p2_depth = p2_depth + (row['distance'] * p2_aim)
elif (row['direction']=='down'):
# increase aim
p2_aim=p2_aim + row['distance']
elif (row['direction']=='up'):
# deincrease aim
p2_aim=p2_aim - row['distance']
p2_position = p2_dist * p2_depth
print (f'answer = {p2_position}')
answer = 2078985210