예제 #1
0
import fileinput
from utils import parse_nums

INF = 1e9
POINTS = []

for line in fileinput.input():
    x, y, dx, dy = parse_nums(line)
    POINTS.append([x, y, dx, dy])

best_x = INF
best_y = INF
seconds = 0

while True:
    min_x = INF
    max_x = -INF
    min_y = INF
    max_y = -INF

    for i, (x, y, dx, dy) in enumerate(POINTS):
        min_x = min(min_x, x)
        max_x = max(max_x, x)
        min_y = min(min_y, y)
        max_y = max(max_y, y)

        POINTS[i][0] += dx
        POINTS[i][1] += dy

    diff_x = max_x - min_x
    diff_y = max_y - min_y
예제 #2
0
# permutations('ABCD', 2)                     AB AC AD BA BC BD CA CB CD DA DB DC
# combinations('ABCD', 2)                     AB AC AD BC BD CD
# combinations_with_replacement('ABCD', 2)    AA AB AC AD BB BC BD CC CD DD

tot = 0
res = []
board = {}
table = new_table(None, width=2, height=4)

# Uncomment for multi-group style inputs. :c
# data = ''.join([line for line in fileinput.input()])
# groups = [g.split('\n') for g in data.split('\n\n')]

for y, line in enumerate(fileinput.input()):
    line = line.strip()
    nums = parse_nums(line)
    data = parse_line(r'', line)
    nums = [int(x) for x in line.split(',')]

    for x, c in enumerate(line):
        board[Point(x, y)] = c

    if y == 0:
        print(data)

print nums

seen = defaultdict(list)

for i, n in enumerate(nums):
    seen[n].append(i)
예제 #3
0
    max_y = 0

    while x <= END_X and y >= END_Y - 30:
        x += vel_x
        y += vel_y
        max_y = max(max_y, y)

        if vel_x > 0:
            vel_x -= 1
        elif vel_x < 0:
            vel_x += 1

        vel_y -= 1

        # We are in the target zone.
        if START_X <= x <= END_X and START_Y <= y <= END_Y:
            return max_y


# Parse problem input.
START_X, END_X, START_Y, END_Y = parse_nums(fileinput.input()[0])

# Compute viable start velocities.
viables = [
    solve(x, y) for y in range(START_Y, -START_Y + 1) for x in range(END_X + 1)
]
viables = [v for v in viables if v is not None]

print "Part 1:", max(viables)
print "Part 2:", sum(1 for v in viables)
예제 #4
0
import fileinput
from collections import Counter, defaultdict

from utils import parse_nums


# Read problem input
EVENTS = sorted(parse_nums(line, negatives=False) for line in fileinput.input())

# Process events
SHIFTS = Counter()
GUARDS = defaultdict(Counter)
curr_id = None
sleep_min = None

for record in EVENTS:
    if len(record) == 6:  # shift begins
        curr_id = int(record[-1])

    elif sleep_min is None:  # falls asleep
        sleep_min = record[-1]

    else:  # wakes up
        minute = record[-1]
        SHIFTS[curr_id] += minute - sleep_min
        for m in range(sleep_min, minute):
            GUARDS[curr_id][m] += 1

        sleep_min = None

# Compute Part 1 answer
예제 #5
0
import fileinput
from utils import parse_nums


def dist(x, y):
    return sum(abs(a - b) for a, b in zip(x, y))


POINTS = [tuple(parse_nums(line)) for line in fileinput.input()]


cliques = [[g] for g in POINTS]
last_len = None

while True:
    if len(cliques) == last_len:
        break

    last_len = len(cliques)

    next_cliques = []
    merged = set()

    for i in range(len(cliques)):
        next_clique = cliques[i][:]

        if i in merged:
            continue

        for j in range(i + 1, len(cliques)):
            for dd in cliques[j]:
예제 #6
0
import fileinput
from utils import parse_nums


class Node:
    def __init__(self, val, n=None, p=None):
        self.val = val
        self.next = n
        self.prev = p


PLAYERS, MARBLES = parse_nums(fileinput.input()[0])
scores = [0] * PLAYERS
player = 0

curr = Node(0)
curr.next = curr
curr.prev = curr

for m in range(1, MARBLES * 100):
    if m % 23 == 0:
        scores[player] += m
        for _ in range(7):
            curr = curr.prev

        scores[player] += curr.val
        curr.prev.next = curr.next
        curr.next.prev = curr.prev
        curr = curr.prev.next
    else:
        curr = curr.next
예제 #7
0
파일: day08.py 프로젝트: iKevinY/advent
import fileinput
from copy import deepcopy
from utils import parse_nums

TAPE = []

for line in fileinput.input():
    ins = line.split(' ')[0]
    TAPE.append([ins, parse_nums(line)])


def emulate(tape, pc=0, acc=0):
    """Returns (acc, pc, loop_detected)"""
    seen = set()
    while pc < len(tape):
        if pc in seen:
            return (acc, pc, True)
        else:
            seen.add(pc)

        ins, ops = tape[pc]

        if ins == 'acc':
            acc += ops[0]
            pc += 1
        elif ins == 'jmp':
            pc += ops[0]
        else:
            pc += 1

    return (acc, pc, False)
예제 #8
0
IMMUNE = []
INFECT = []
BOOST = 0
DEBUG = False

on_infection = False

for i, line in enumerate(fileinput.input()):
    line = line.strip()

    if line == 'Infection:':
        on_infection = True
        continue

    try:
        _count, hp, dmg, initiative = parse_nums(line, negatives=False)
    except Exception:
        continue
    clauses = next(iter(re.findall(r'(\(.+\))', line)), None)
    type = re.findall(r'(\S+) damage', line)
    type = next(iter(type), None)

    parts = (clauses or '').replace(',', '').replace('(',
                                                     '').replace(')',
                                                                 '').split(';')
    weaknesses = []
    immunities = []

    if parts[0] != '':
        for part in parts:
            things = part.split()
예제 #9
0
파일: day06.py 프로젝트: iKevinY/advent
import fileinput
from collections import Counter

from utils import Point, DIRS_4, parse_nums


COORDS = []

for line in fileinput.input():
    x, y = parse_nums(line)
    COORDS.append((x, y))

X, Y = zip(*COORDS)

ASSIGNS = {}
REGIONS = Counter()
SAFETY = Counter()

for y in range(min(Y), max(Y)):
    for x in range(min(X), max(X)):
        p = Point(x, y)
        total_distance = 0
        to_point = {}

        for (xx, yy) in COORDS:
            q = Point(xx, yy)
            dist = p.to_manhattan(q)
            to_point[q] = dist
            total_distance += dist

        SAFETY[p] = total_distance