목차

Advent Of Code

연도별 문서

문제 스타일

유틸리티 코드

import os
import requests
import sys


FOLDER = './AdventOfCode/'
YEAR = 2023

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
HEADERS = {'User-Agent': USER_AGENT}
SESSION_ID_FILE = FOLDER + 'session.cookie'

TEMPLATE = '''"""Solution code for "Advent of Code {0} Day {1}".

- Problem link: https://adventofcode.com/{0}/day/{1}

Tags: [XXX]
"""

def solve_part1(lines):
    pass

    
def solve_part2(lines):
    pass


def main():
    with open('./AdventOfCode/{0}/day{1}.txt', encoding='utf-8') as file:
        lines = file.read().split('\\n')
    print('[PART 1]')
    solve_part1(lines)
    print('[PART 2]')
    solve_part2(lines)    


if __name__ == '__main__':
    main()
'''


def get_session_id(filename):
    with open(filename, encoding='utf-8') as f:
        return f.read().strip()


def get_url(year, day):
    return f'https://adventofcode.com/{year}/day/{day}/input'


def get_cookies():
    session = get_session_id(SESSION_ID_FILE)
    return {'session': session}


def create_input_file(year, day):
    path = f'{FOLDER}{year}/day{day}.txt'
    if os.path.exists(path):
        print(path + ' already exists.')
        return

    url = get_url(year, day)
    cookies = get_cookies()
    response = requests.get(url, headers=HEADERS, cookies=cookies)
    if not response.ok:
        raise RuntimeError(
            f'Request failed\n\tstatus code: {response.status_code}\n\tmessage: {response.content}'
        )
    with open(path, 'w', encoding='utf-8') as f:
        f.write(response.text[:-1])


def create_source_file(year, day):
    path = f'{FOLDER}{year}/day{day}.py'
    if os.path.exists(path):
        print(path + ' already exists.')
        return

    with open(path, 'w', encoding='utf-8') as f:
        f.write(TEMPLATE.format(year, day))


def main():
    if len(sys.argv) != 2:
        year_and_day = input(f'Input day (or year/day, if year != {YEAR}): ')
    else:
        year_and_day = sys.argv[1]
    if '/' in year_and_day:
        year, day = year_and_day.split('/')
    else:
        year, day = YEAR, int(year_and_day)

    create_input_file(year, day)
    create_source_file(year, day)


if __name__ == '__main__':
    main()