Esempio n. 1
0
def main():
    tree = load_input('input.txt')[0].split()
    tree = [int(q) for q in tree]

    part1, part2 = treeverse(tree)

    print('Part 1:', part1)
    print('Part 2:', part2)
Esempio n. 2
0
    def test_cutdown_drinks(self):
        data = utils.load_input('./input/users.json')

        # check if every letter is lowercase
        for drink in data[0]['drinks']:
            for c in drink:
                # cheeky ignore spaces
                if c != ' ':
                    self.assertEqual(c.islower(), True)
Esempio n. 3
0
def main():
    # Get the number of players, and the (base) highest marble0
    players, _, _, _, _, _, base_highest_marble, _ = load_input(
        'input.txt')[0].split()

    # convert to integers
    players = int(players)
    base_highest_marble = int(base_highest_marble)

    print('Part 1', winning_score(players, base_highest_marble))
    print('Part 2', winning_score(players, base_highest_marble * 100))
Esempio n. 4
0
def main():
    board = load_input('input.txt')

    k = 3
    while True:
        all_elves_survived, outcome = simulation(board, k)
        if k == 3:
            print('Part 1:', outcome)
        elif all_elves_survived:
            # this is the first attack damage for which all elves survived
            print('Part 2:', outcome)
            break
        k += 1
Esempio n. 5
0
def main():
    """
    Barebones, I would like to add proper inputs etc,

    """
    # load input files
    venues = utils.load_input('./input/venues.json')
    users = utils.load_input('./input/users.json')

    # input for further down
    parsed_acceptable_venues, parsed_unacceptable_venues = _parse_venues(
        venues, users)

    # find un/acceptable venues
    acceptable_venues = _find_acceptable_venues(parsed_acceptable_venues,
                                                parsed_unacceptable_venues)

    # output acceptable events
    _output_acceptable_venues(acceptable_venues)

    # output unacceptable events
    _output_unacceptable_venues(parsed_unacceptable_venues)
Esempio n. 6
0
def main():
    # get the list of step orderings
    key = int(load_input('input.txt')[0])

    # get the 10 recipes after our puzzle input
    recipes = get_recipes(key + 10)
    print('Part 1:', ''.join(mapstr(recipes[key:key + 10])))

    # we keep generating recipes until our key appears
    recipes = get_recipes(25000000)

    # find the first place the key occurs in our recipe list
    print('Part 2:', ''.join(mapstr(recipes)).find(str(key)))
Esempio n. 7
0
def main():
    # get the list of step orderings
    track = load_input('input.txt')
    board = defaultdict(int)
    carts = {}
    k = 0

    for (y, line) in enumerate(track):
        for (x, c) in enumerate(line):
            b = None
            if c == '|':
                b = 1
            if c == '-':
                b = 2
            if c == '/':
                b = 3
            if c == '\\':
                b = 4
            if c == '+':
                b = 5
            if c == '^':
                carts[(x, y)] = ['N', 0, k]
                b = 1
                k += 1
            if c == 'v':
                carts[(x, y)] = ['S', 0, k]
                b = 1
                k += 1
            if c == '>':
                carts[(x, y)] = ['E', 0, k]
                b = 2
                k += 1
            if c == '<':
                carts[(x, y)] = ['W', 0, k]
                b = 2
                k += 1
            if b is not None:
                board[(x, y)] = b

    has_crashed = False
    while True:
        carts, deleted_keys = tick(board, carts)
        # when the first crash occurs, we obtain our solution to part 1
        if not has_crashed and len(deleted_keys) > 0:
            has_crashed = True
            print("Part 1:", deleted_keys[0])

        # when only one cart remains, we have our solution to part 2
        if len(carts) == 1:
            print("Part 2:", list(carts.keys())[0])
            break
Esempio n. 8
0
def main():
    puzzle_input = load_input('input.txt')

    _, pts = simulate(puzzle_input, 0)
    print('Part 1:', pts)

    # look for the smallest boost where the immune system outright wins
    boost = 0
    while True:
        winner, c = simulate(puzzle_input, boost)
        if winner == 'immune':
            print('Part 2:', c)
            break
        boost += 1
Esempio n. 9
0
def main():
    land = defaultdict(int)
    for (y, line) in enumerate(load_input('input.txt')):
        for (x, char) in enumerate(line):
            if char == '.':
                w = 0
            elif char == '|':
                w = 1
            elif char == '#':
                w = 2
            land[(x, y)] = w

    print('Part 1:', simulate(land, 10))
    print('Part 2:', simulate(land, 1000000000))
Esempio n. 10
0
def main():
    # get the list of step orderings
    serial_number = int(load_input('input.txt')[0])
    sat = summed_area_table(serial_number)

    # for part 2
    max_pos = None
    max_power = None
    max_size = None

    for size in range(3, 300):
        x, y, power = max_power_level(size, sat)
        if size == 3:
            print(f"Part 1: {x}, {y}, Power: {power}")
        if max_power is None or power > max_power:
            max_power = power
            max_pos = (x, y)
            max_size = size

    print(f"Part 2: {max_pos[0]}, {max_pos[1]}, Size: {max_size}")
Esempio n. 11
0
def main():
    # get the list of step orderings
    points = load_input('input.txt')
    positions = {}
    position_set = set()
    velocities = {}

    # extract the four digits out of each input line
    for (k, line) in enumerate(points):
        x, y, xv, yv = get_numbers(line)

        positions[k] = (x, y)
        position_set.add((x, y))
        velocities[k] = (xv, yv)

    m = 0
    while True:
        ymin = min(t[1] for t in position_set)
        ymax = max(t[1] for t in position_set)

        ht = abs(ymax - ymin)
        # the lights align perfectly when the height is 9
        # its unclear if this always achieves the correct result
        if ht == 9:
            xmin = min(t[0] for t in position_set)
            xmax = max(t[0] for t in position_set)
            print_blocks(position_set, xmin, xmax, ymin, ymax)
            break

        # move the lights by their velocities
        # updating the set of positions
        position_set = set()

        for idx in positions:
            positions[idx] = (positions[idx][0] + velocities[idx][0],
                              positions[idx][1] + velocities[idx][1])
            position_set.add(positions[idx])

        m += 1
    return m
Esempio n. 12
0
def main():
    door = map_doors((0, 0), load_input('input.txt')[0])
    rooms = {}

    # link up each of the rooms
    for start, end in door:
        if start not in rooms:
            rooms[start] = Room(start)
        if end not in rooms:
            rooms[end] = Room(end)
        rooms[start].add_neighbour(rooms[end])
        rooms[end].add_neighbour(rooms[start])

    # compute the shortest distance from (0,0) to every room
    distances = {(0, 0): 0}
    to_process = set([rooms[(0, 0)]])

    while len(to_process) > 0:
        room = to_process.pop()

        for adjacent_room in room.neighbours:
            if adjacent_room.pos not in distances:
                distances[adjacent_room.pos] = distances[room.pos] + 1
                to_process.add(adjacent_room)
            else:
                if distances[room.pos] + 1 < distances[adjacent_room.pos]:
                    distances[adjacent_room.pos] = distances[room.pos] + 1
                    to_process.add(adjacent_room)

    c = 0
    for pos in distances:
        # count the number of points that are at least a distance 1000 away
        if distances[pos] >= 1000:
            c += 1

    m = max(distances, key=distances.get)
    print('Part 1:', distances[m])
    print('Part 2:', c)
Esempio n. 13
0
def main():
    # get the list of step orderings
    steps = load_input('input.txt')

    # write down the graph
    mapped_to = defaultdict(list)
    keys = set()
    for line in steps:
        x = line.split()

        # step a must be finished before step b
        a = x[1]
        b = x[7]

        # add the keys
        keys.add(a)
        keys.add(b)

        # a is mapped to b
        mapped_to[b].append(a)

    print('Part 1:', part1(keys.copy(), mapped_to.copy()))
    print('Part 2:', part2(keys.copy(), mapped_to.copy()))
Esempio n. 14
0
def main():
    lines = load_input('https://pastebin.com/raw/ebDxSugK')
    print(part_one(lines))
    print(part_two(lines))
Esempio n. 15
0
from utils import load_input, get_numbers, manhattan_distance
import numpy as np


def triangular(n):
    return n*(n+1) // 2


v = {}
a = {}
p = {}

for (k,line) in enumerate(load_input('puzzle_inputs/Day20.txt')):
    px,py,pz,vx,vy,vz,ax,ay,az = get_numbers(line)
    v[k] = (vx,vy,vz)
    a[k] = (ax,ay,az)
    p[k] = (px,py,pz)

v = np.array(list(v.values()), dtype='int64')
a = np.array(list(a.values()), dtype='int64')
p = np.array(list(p.values()), dtype='int64')

# part 1
# a closed for for the position after t steps is
# p_i(t) = p_i(0) + t * v_i + triangular(t) * a_i
large_number = 500000000

d = p+large_number*v + triangular(large_number)*a

print('Part 1:', min(enumerate(d),key=lambda q:manhattan_distance(q[1],(0,0,0)))[0])
Esempio n. 16
0
 def test_cutdown_user_wont_eat(self):
     data = utils.load_input('./input/users.json')
     self.assertEqual(data[0]['wont_eat'][0], 'fish')
Esempio n. 17
0
 def test_raises_file_not_found(self):
     with self.assertRaises(FileNotFoundError) as context:
         utils.load_input('foo.json')
Esempio n. 18
0
 def test_cutdown_venues_food(self):
     data = utils.load_input('./input/venues.json')
     self.assertEqual(data[0]['food'][0], 'mexican')
Esempio n. 19
0
    points_in_constellation = set()
    points_remaining = set(points)
    # basically we pick a point that isn't in a constellation, and then keep working
    # away from that point until we've found the entire constellation
    while True:
        # no more points remaining!
        if len(points_remaining) == 0:
            break

        p = points_remaining.pop()
        to_process = set([p])
        points_in_constellation.add(p)

        while len(to_process) > 0:
            p = to_process.pop()

            # get all the points that are within a distance of 3 of our current processing points
            qs = {q for q in points_remaining if distances[p][q] <= 3}

            points_remaining = points_remaining.difference(qs)
            points_in_constellation = points_in_constellation.union(qs)
            to_process = to_process.union(qs)

        constellations += 1

    return constellations


if __name__ == '__main__':
    print('Part 1:', main(load_input('input.txt')))
Esempio n. 20
0
        return []

    if idx + length < len(li):
        return li[:idx] + li[idx:idx+length][::-1] + li[idx+length:]
    else:
        # have some overflow
        overflow = length - (len(li) - idx)
        sublist = (li[idx:] + li[:overflow])[::-1]

        return sublist[len(li)-idx:] + li[overflow:idx] + sublist[:len(li)-idx]

if __name__ == '__main__':
    numbers = list(range(256))
    current_position = 0
    skip_size = 0
    lengths = get_numbers(load_input('puzzle_inputs/Day10.txt')[0])

    for length in lengths:
        numbers = wrap_reverse(numbers, current_position % len(numbers), length)
        current_position += length + skip_size
        skip_size += 1

    print('Part 1:', numbers[0] * numbers[1])

    # PART 2
    lengths = [ord(c) for c in load_input('puzzle_inputs/Day10.txt')[0]]
    lengths.extend([17, 31, 73, 47, 23])

    current_position = 0
    skip_size = 0
    numbers = list(range(256))
Esempio n. 21
0
def main():
    lines = load_input('https://pastebin.com/raw/VdZiDjRn')
    guards, ans = part_one(lines)

    print(part_two(guards))
Esempio n. 22
0
    	Where the serial port is. Should be in the form of /dev/cu.usbmodem1431 
    	or similar
    """)
    args = parser.parse_args()
    room_in = args.room
    loc = args.location
    serial_port = args.serial


## Serial and Logging Stufff
ser = serial.Serial(serial_port, 9600)
logging.basicConfig(filename='arudino_recorder.log',level=logging.DEBUG)

while True:
 	try:
 		 load_input(parse_input(ser.readline()),room_in,loc)
 	except serial.serialutil.SerialException:
 		 logging.warning("Arudino Failed to Report Data")
 		 pass
 	except IndexError:
		 logging.warning("Bad Input Error")
		 pass
	except sqlalchemy.exc.DataError:
		 logging.warning("SQL Alchemy Error")
		 pass
	except KeyboardInterrupt:
    	 print "You have quit the program. It will now exit. Goodbye"
         sys.exit()
	except:
		 print sys.exc_info()[0]
 		 logging.info(sys.exc_info()[0])
Esempio n. 23
0
from utils import load_input
from cartesian import left, right, up, down


def b(pos):
    if pos[1] < 0 or pos[1] >= len(
            puzzle_input) or pos[0] < 0 or pos[0] >= len(puzzle_input[pos[1]]):
        return ' '
    return puzzle_input[pos[1]][pos[0]]


puzzle_input = load_input('puzzle_inputs/Day19.txt')

pos = (puzzle_input[0].index('|'), 0)
direction = down

word = ''
steps = 1

while True:
    # if we're on a letter, add it to our word
    if b(pos).isalpha():
        word += b(pos)

    dpos = direction(pos)
    # if we're ok to move in our current direction, then do so
    if b(dpos) != ' ':
        pos = direction(pos)
        steps += 1
    else:
        # otherwise, change directions
Esempio n. 24
0
 def load_data(self, debug=False):
     """Loads train/valid/test data"""
     self.train, self.word_embedding, self.max_sen_len, self.input_vocab_size, self.vocab, self.ivocab = utils.load_input(
         self.config)
     print '---> Config Vocab Size is ..', self.config.vocab_size
     print '---> Config Hidden Layer Size is ..', self.config.hidden_size
     print '---> Config Word Vector Size is ..', self.config.embed_size
     print '---> Input Vocab Size is ..', self.input_vocab_size
Esempio n. 25
0
def main():
    lines = load_input('https://pastebin.com/raw/HSnu5ViM')
    print(part_one(lines))
    print(part_two(lines))
Esempio n. 26
0

def part_two(string):
    lets = 'qwertyuiopasdfghjklzxcvbnm'
    small = 99999999

    for l in lets:
        curr = part_one(string.replace(l, '').replace(l.upper(), ''), combos())
        if curr < small:
            small = curr
    return small


def combos():
    combs = set()
    lets = 'qwertyuiopasdfghjklzxcvbnm'

    for l in lets:
        combs.add(f'{l}{l.upper()}')
    for l in lets.upper():
        combs.add(f'{l}{l.lower()}')
    return combs

string = load_input('https://pastebin.com/raw/TpG550mX', as_string=True)
combs = combos()

print(timeit.timeit('part_one(string, combs)', globals=globals(), number=1000))

# if __name__ == '__main__':
#     main()
Esempio n. 27
0
from utils import load_input, get_numbers, manhattan_distance


class Nanobot:
    def __init__(self, _x, _y, _z, _r):
        self.x = _x
        self.y = _y
        self.z = _z
        self.r = _r

    def __repr__(self):
        return str((self.x, self.y, self.z, self.r))


puzzle_input = load_input('input.txt')

nanobots = []

for line in puzzle_input:
    x, y, z, r = get_numbers(line)
    nanobots.append(Nanobot(x, y, z, r))

nanobots.sort(key=lambda q: q.r, reverse=True)

# PART 1
r = nanobots[0]
nanobots_in_range = 0

for bot in nanobots:
    if manhattan_distance((r.x, r.y, r.z), (bot.x, bot.y, bot.z)) <= r.r:
        nanobots_in_range += 1
Esempio n. 28
0
def main():
    # process the input into a list of integers
    differences = [int(q) for q in load_input('input.txt')]

    print('Part 1:', part1(differences))
    print('Part 2:', part2(differences))
Esempio n. 29
0
def main():
    initial_polymer = load_input('input.txt')[0]

    print('Part 1:', part1(initial_polymer))
    print('Part 2:', part2(initial_polymer))
Esempio n. 30
0
from utils import load_input
from collections import defaultdict
from cartesian import left, right, up, down, turn_left, turn_right

grid = defaultdict(int)
puzzle_input = load_input('puzzle_inputs/Day22.txt')

for (y, line) in enumerate(puzzle_input):
    for (x, char) in enumerate(line):
        if char == '#':
            grid[(x, y)] = 1

# initially start at the centre of our input, facing up
pos = (len(puzzle_input) // 2, len(puzzle_input) // 2)
direction = up

burst = 0
infections = 0
while burst < 10000:
    x, y = pos
    if grid[(x, y)] == 1:
        direction = turn_right(direction)
    else:
        infections += 1
        direction = turn_left(direction)

    grid[(x, y)] = 1 - grid[(x, y)]
    pos = direction(pos)
    burst += 1

print('Part 1:', infections)
Esempio n. 31
0
def main():
    operations = [addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr]

    puzzle = load_input('input.txt')

    before = None
    instruction = None
    part1_count = 0
    possible_int = {}

    for (k,line) in enumerate(puzzle):
        if k % 4 == 0:
            before = get_numbers(line)
        if k % 4 == 1:
            instruction = get_numbers(line)
        if k % 4 == 2:
            after = get_numbers(line)
            opcode = instruction[0]

            # get the operations that this instruction could correspond to
            possible = check(before,after,instruction[1:], operations)

            # count the number of samples that behave like three or more opcodes
            if len(possible) >= 3:
                part1_count += 1

            # we keep intersecting the list of possible operations based on the result of each input
            if opcode not in possible_int:
                possible_int[opcode] = possible
            else:
                possible_int[opcode] = intersection(possible_int[opcode],possible)

    # for part 1, count how many sample in our input behave like three or more opcodes
    print('Part 1:', part1_count)

    secured = []
    # for part 2, we need to figure out which opcode corresponds to which operation
    # at each stage, there is always (at least) one opcode that we can deduce
    while len(secured) < 15:
        for key in possible_int:
            # if we've already figured this one out, skip it
            if key in secured:
                continue

            # if there's only 1 possibility for what this opcode could be, then we're done!
            if len(possible_int[key]) == 1:
                secured.append(key)
                new_possible_int = possible_int.copy()
                # remove this operation as a possibility for all other opcodes
                for k in possible_int:
                    if k == key:
                        continue
                    if possible_int[key][0] in new_possible_int[k]:
                        new_possible_int[k].remove(possible_int[key][0])
                possible_int = new_possible_int
                break

    # apply the operations to our puzzle input
    registers = [0,0,0,0]
    for line in load_input('input2.txt'):
        op, a, b, c = get_numbers(line)
        registers = operations[possible_int[op][0]](registers,a,b,c)

    print('Part 2:', registers[0])