DEV Community

Cover image for Automating Advent of Code

Posted on

Automating Advent of Code

Last year, December became my favorite month of the year when I stumbled upon something called Advent of Code. It's a calendar that each day presents 2 new coding challenges for you to crack. The goal is to solve these using any programming language you want, in order to save christmas.

Link to Advent of Code

This year I got tired of creating all the files, folders and download the input everyday, that I finally decided to do something about it.

So what does a lazy coder do? We automate!

I make 1 folder for each day containing 2 files for each part. I have a where I test code snippets and I create a testinput.txt for any test input. Then I download the input file for the day and add it accordingly.

Disclaimer: I've only tested this on Windows so your mileage may vary.

Prerequisites: Python 3, Selenium, Chrome Driver (or your driver of choice)

Link to github

from selenium import webdriver
from import Options
import os, sys

#Verify we're getting input
if len(sys.argv) != 2:
    print('Missing day number. Run e.g:')
    print('python 13')

day = str(sys.argv[1])
path = str(os.getcwd()) + "/day" + day
#Create folder from input
except OSError:
    print ("Creation of the directory %s failed" % path)

#Create 4 empty files
lista = ["/", "/", "/testinput.txt"]
for i in lista:
    open(path + i, 'a').close()

#Create and Write to
part1 = path + "/"
f = open(part1, "a")
f.write('data = open("input.txt").read().split("\\n")')

chrome_options = Options()

# Replace value with your session cookie for AoC
session_cookie = {"name": "session", "value": "<Session_cookie>"}
# initialize driver object and change the <path_to_chrome_driver> depending on your directory where your chromedriver should be
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path="<path_to_chrome_driver>")

# URLs we need
url = ""
url_input = "" + day + "/input"

# get request to target the site selenium is active on, add our cookies and go to input

# Find our text input on the input page, "pre" is our tag ID
content = driver.find_element_by_tag_name("pre").text

# Save content to file
path = path + "/input.txt"
f = open(path, "a")
for line in content:
# Remember to quit the driver

print(str(path) + " and adjacent files created!")
Enter fullscreen mode Exit fullscreen mode

Feel free to use this and adjust it to your own liking. Make sure to edit the 2 fields in the code:

  1. Session cookie
  2. path_to_chrome_driver

Run it by executing it together with a number for the day you're planning to do, e.g:

python 25
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

potentialstyx profile image

Nice! I'll try to combine with another script to auto create and download input files. And time + run them