my solutions for advent of code 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.2 KiB

import re
#create a class to store the map
class plan:
def __init__(self):
self.grid = []
self.goTo = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def addLine(self, inputLine):
inputLine = inputLine.replace(' ', '+')
self.grid.append(list(inputLine))
def testPrint(self):
for line in self.grid:
for point in line:
print(point, end = ' ')
print('\n')
def setStart(self):
self.direction = 0
self.column = self.grid[0].index('.')
self.row = 0
maxL = 0
for line in self.grid:
if len(line) > maxL:
maxL = len(line)
for i in range(len(self.grid)):
while len(self.grid[i]) < maxL:
self.grid[i].append('+')
def getInstruction(self, instruction):
if instruction.isnumeric():
self.move(int(instruction))
if instruction.isalpha():
self.turn(instruction)
def turn(self, direction):
if direction == 'L':
self.direction -= 1
if self.direction < 0:
self.direction = 3
elif direction == 'R':
self.direction = (self.direction + 1) % 4
def move(self, distance):
for _ in range(distance):
nextRow = self.row + self.goTo[self.direction][0]
nextCol = self.column + self.goTo[self.direction][1]
if nextRow < 0 or nextCol < 0 or nextRow >= len(self.grid) or nextCol >= len(self.grid[nextRow]) or self.grid[nextRow][nextCol] == '+':
nextRow, nextCol = self.wrapAround(nextRow, nextCol)
if self.grid[nextRow][nextCol] == '#':
return
self.column = nextCol
self.row = nextRow
def wrapAround(self, nextRow, nextCol):
if self.direction == 0:
for i in range(len(self.grid[nextRow])):
if self.grid[nextRow][i] in ['.', '#']:
nextCol = i
break
elif self.direction == 1:
for i in range(len(self.grid)):
if self.grid[i][nextCol] in ['.', '#']:
nextRow = i
break
elif self.direction == 2:
for i in range(len(self.grid[nextRow])-1, 0, -1):
if self.grid[nextRow][i] in ['.', '#']:
nextCol = i
break
elif self.direction == 3:
for i in range(len(self.grid)-1, 0, -1):
if self.grid[i][nextCol] in ['.', '#']:
nextRow = i
break
return nextRow, nextCol
def getPassword(self):
return (self.column + 1)*4 + (self.row + 1)*1000 + self.direction
#create an object of the map
path = plan()
# reading input and inserting it into the map
with open('input22.txt','r') as f:
inp = f.read().splitlines(keepends=False)
for line in inp:
if line == '':
break
path.addLine(line)
instructionSet = inp[-1]
instructionSet = re.split('(\d+)', instructionSet)
path.setStart()
#go through the instructions
for instruction in instructionSet:
path.getInstruction(instruction)
#path.testPrint()
print(path.column + 1, path.row + 1, path.direction, sep = '---')
print(path.getPassword())