Esempio n. 1
0
def parse_army(line):
    units, hp, dmg, initiative = get_numbers(line)

    # damage type?
    dmg_type = line.split(" damage")[0].split(" ")[-1]

    # weaknesses
    weaknesses = []
    if ('weak' in line):
        weaknesses = line.split('weak to ')[1]
        if (';' in weaknesses):
            weaknesses = weaknesses.split(';')[0]
        elif (')' in weaknesses):
            weaknesses = weaknesses.split(')')[0]
        weaknesses = weaknesses.split(', ')

    # immunities
    immunities = []
    if ('immune' in line):
        immunities = line.split('immune to ')[1]
        if (';' in immunities):
            immunities = immunities.split(';')[0]
        elif (')' in immunities):
            immunities = immunities.split(')')[0]
        immunities = immunities.split(', ')

    return units, hp, dmg, dmg_type, initiative, weaknesses, immunities
Esempio n. 2
0
def create_message(corpus, data, msg0=None):
    from email import Charset, Parser, MIMEMessage

    if not isinstance(data, unicode):
        raise TypeError("data must be a unicode.")
    p = Parser.FeedParser()
    p.feed(data)
    msg1 = p.close()
    csmap = Charset.Charset(config.MESSAGE_CHARSET)
    attach_msgs = []
    # Re-encode the headers.
    headers = []
    labels = []
    for (k, v) in msg1.items():
        v = rmsp(v)
        if not v:
            continue
        kl = k.lower()
        if kl == "x-forward-msg":
            attach_msgs.extend(get_numbers(v))
            continue
        if kl == "label":
            labels = v.split(",")
            continue
        headers.append((k.encode("ascii", "strict"), encode_header(v, csmap)))
    # Remove all the existing headers.
    for k in msg1.keys():
        del msg1[k]
    # Reattach the headers.
    for (k, v) in headers:
        msg1[k] = v
    # Change the body.
    data = msg1.get_payload(decode=False)
    try:
        # First try to encode with us-ascii.
        data.encode("ascii", "strict")
        # Succeed.
        msg1.set_charset("ascii")
    except UnicodeError:
        # Re-encode the body.
        if not csmap.output_charset:
            csmap = Charset.Charset("utf-8")
        msg1.set_charset(str(csmap.output_charset))
        data = data.encode(str(csmap.output_codec), "replace")
    msg1.set_payload(data)
    # Attach other messages (for forwarding).
    if attach_msgs:
        for loc in attach_msgs:
            p = Parser.FeedParser()
            p.feed(corpus.get_message(loc))
            msg1 = mime_add(msg1, MIMEMessage.MIMEMessage(p.close()))
    # Integrate other mime objects.
    if msg0 and msg0.is_multipart():
        for obj in msg0.get_payload()[1:]:
            msg1 = mime_add(msg1, obj)
    validate_message_structure(msg1)
    return (msg1, labels)
Esempio n. 3
0
def create_message(corpus, data, msg0=None):
    from email import Charset, Parser, MIMEMessage
    if not isinstance(data, unicode):
        raise TypeError('data must be a unicode.')
    p = Parser.FeedParser()
    p.feed(data)
    msg1 = p.close()
    csmap = Charset.Charset(config.MESSAGE_CHARSET)
    attach_msgs = []
    # Re-encode the headers.
    headers = []
    labels = []
    for (k, v) in msg1.items():
        v = rmsp(v)
        if not v: continue
        kl = k.lower()
        if kl == 'x-forward-msg':
            attach_msgs.extend(get_numbers(v))
            continue
        if kl == 'label':
            labels = v.split(',')
            continue
        headers.append((k.encode('ascii', 'strict'), encode_header(v, csmap)))
    # Remove all the existing headers.
    for k in msg1.keys():
        del msg1[k]
    # Reattach the headers.
    for (k, v) in headers:
        msg1[k] = v
    # Change the body.
    data = msg1.get_payload(decode=False)
    try:
        # First try to encode with us-ascii.
        data.encode('ascii', 'strict')
        # Succeed.
        msg1.set_charset('ascii')
    except UnicodeError:
        # Re-encode the body.
        if not csmap.output_charset:
            csmap = Charset.Charset('utf-8')
        msg1.set_charset(str(csmap.output_charset))
        data = data.encode(str(csmap.output_codec), 'replace')
    msg1.set_payload(data)
    # Attach other messages (for forwarding).
    if attach_msgs:
        for loc in attach_msgs:
            p = Parser.FeedParser()
            p.feed(corpus.get_message(loc))
            msg1 = mime_add(msg1, MIMEMessage.MIMEMessage(p.close()))
    # Integrate other mime objects.
    if msg0 and msg0.is_multipart():
        for obj in msg0.get_payload()[1:]:
            msg1 = mime_add(msg1, obj)
    validate_message_structure(msg1)
    return (msg1, labels)
Esempio n. 4
0
def main(puzzle_input):
    points = []

    for line in puzzle_input:
        points.append(tuple(get_numbers((line))))

    # compute the distance between every pair of points
    distances = {
        p: {q: manhattan_distance(p, q)
            for q in points}
        for p in points
    }

    # for each point, find the constellation of points that it contains
    constellations = 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
Esempio n. 5
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. 6
0
from utils import load_input, get_numbers
from collections import defaultdict

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

r = defaultdict(int)
code = ""
current_max = 0

for line in puzzle_input:
    delta, condition = get_numbers(line)
    operation = line.split()[1]
    variable = line.split()[0]
    condition_variable = line.split(' if ')[1].split(' ')[0]
    conditional = line.split(f'if {condition_variable} ')[1].split()[0]

    # we translate the code to pure python
    code = f"if r['{condition_variable}'] {conditional} {condition}:\n"

    if operation == 'inc':
        code += f"\tr['{variable}'] += {delta}\n"
    else:
        code += f"\tr['{variable}'] -= {delta}\n"

    # evalate, then check what the maximum value of any register is
    exec(code)

    m = r[max(r, key=r.get)]
    if m > current_max:
        current_max = m
Esempio n. 7
0
def main():
    puzzle_input = load_input('input.txt')
    spring = defaultdict(str)
    spring[(500,0)] = '|'

    for line in puzzle_input:
        char = line[0]
        pos, a, b = get_numbers(line)
        if char == 'x':
            for y in range(a,b+1):
                spring[(pos,y)] = '#'
        else:
            for x in range(a,b+1):
                spring[(x,pos)] = '#'
    spring[(500,1)] = '|'

    ymaxx = max(q[1] for q in spring)

    # now how do we want to do this
    current_sources = set([(500,1)])

    while len(current_sources) > 0:
        source = current_sources.pop()

        # if we're past the maximum y, just stop
        if source[1] > ymaxx+10:
            continue

        # if there is no spot underneath, just move down
        d = down(source)
        if spring[d] == '':
            spring[d] = '|'
            current_sources.add(d)
            continue

        # if there is a '|' underneath, probably just ignore this?
        if spring[d] == '|':
            continue

        # there is a spot underneath - try to flow as far left & right as possible
        left_wall = None
        right_wall = None

        x, y = source
        current_x = x+1
        while True:
            current_x -= 1
            pos = (current_x,y)

            # if there's a source block above this point
            # then don't do anything further in this direction
            if pos != source and up(pos) in current_sources:
                left_wall = current_x+1
                break

            if pos != source and (pos in current_sources):
                break

            if pos != source and (spring[down(pos)] == '|' or down(pos) in current_sources):
                break

            spring[pos] = '|'

            # if there is a spot below, then we can flow there
            if spring[down(pos)] == '':
                spring[down(pos)] = '|'
                current_sources.add(down(pos))
                break

            # if theres a wall to our left, then we can't flow any further
            if spring[left(pos)] == '#':
                left_wall = current_x
                break

        current_x = x-1
        while True:
            current_x += 1
            pos = (current_x, y)

            # if there's a source block above this point
            # then don't do anything further in this direction
            if pos != source and up(pos) in current_sources:
                right_wall = current_x - 1
                break

            if pos != source and pos in current_sources:
                break

            if pos != source and (spring[down(pos)] == '|' or down(pos) in current_sources):
                break

            spring[pos] = '|'

            if spring[down(pos)] == '':
                spring[down(pos)] = '|'
                current_sources.add(down(pos))
                break


            # if theres a wall to oru right, then we can't flow any further
            if spring[right(pos)] == '#':
                right_wall = current_x
                break

        # we have a still water layer
        # mark all flowing water blocks above our still layer
        # as potential sources
        if left_wall is not None and right_wall is not None:
            for current_x in range(left_wall,right_wall+1):
                pos = (current_x, y)
                spring[pos] = '~'
                if spring[up(pos)] == '|':
                    current_sources.add(up(pos))

    c = Counter([spring[q] for q in spring if q[1] >= 0 and q[1] < ymaxx])

    print('Part 1:', c['|'] + c['~'])
    print('Part 2:', c['~'])
Esempio n. 8
0
    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

print('Part 1:', nanobots_in_range)

# PART 2
Esempio n. 9
0
def result():
    if request.method == 'POST':
        if request.form.get('post') == "search_results":
            #search on results
            any_key = request.form['rany_key']
            all_key = request.form['rall_key']
            if session['resumes'] == []:
                resumes = request.form.getlist('found_resumes')
                session['resumes'] = resumes
            else:
                resumes = session['resumes']
            any_key_list = any_key.split(",")
            all_key_list = all_key.split(",")
            found_candidates = []
            filter_list = []
            filter_link = []
            total = 0
            total_final = 0
            keywords_matched = []
            from models import Candidate
            for res in resumes:
                cand = Candidate.query.filter_by(resume=res).first()
                found_candidates.append(cand)

            for cand in found_candidates:
                total_final = total_final + 1
                if check_any(cand, any_key_list) == 1 and check_all(
                        cand, all_key_list) == 1:
                    filter_list.append(cand)
                    total = total + 1

            keywords_matched.append("| ".join(any_key_list))
            if all_key_list:
                keywords_matched.append("| ")
            keywords_matched.append("| ".join(all_key_list))

            if len(filter_list) == 0:
                empty = "NO MATCHES FOUND"
                filter_link = []
                return render_template('result.html',
                                       result=filter_list,
                                       skills="[ ]",
                                       exp=",",
                                       key=" ".join(keywords_matched),
                                       items=len(filter_list),
                                       count=str(total) + "/" +
                                       str(total_final),
                                       empty=empty,
                                       url=filter_link,
                                       all=all_key,
                                       any=any_key)
            else:

                filter_link = []
                for cand in filter_list:
                    url_link = cand.resume
                    filter_link.append(url_link.split("/")[-1])
                result_list = rank_resume(filter_list, [], all_key_list,
                                          any_key_list)
                return render_template('result.html',
                                       result=result_list,
                                       skills="[ ]",
                                       exp=",",
                                       key=" ".join(keywords_matched),
                                       items=len(filter_list),
                                       count=str(total) + "/" +
                                       str(total_final),
                                       url=filter_link,
                                       all=all_key,
                                       any=any_key)

        else:
            session['resumes'] = []
            skill = request.form.getlist('skill')
            skill_exp = request.form.getlist('skill_exp')
            skill_cond = request.form['skill_condition']
            skill_iter = request.form.get('skill_full')
            any_key = request.form['any_key']
            all_key = request.form['all_key']
            min_expyear = request.form['min_expyear']
            max_expyear = request.form['max_expyear']

            #search for skill and exp

            filter_list = []
            filter_link = []
            total = 0
            total_final = 0
            keys_matched = []
            exp_matched = ""
            keywords_matched = []
            mini = min_expyear
            maxi = max_expyear
            if str(min_expyear) == '':
                min_expyear = "0"
            if str(max_expyear) == '':
                max_expyear = "10000"

            any_key_list = any_key.split(",")
            all_key_list = all_key.split(",")

            from models import Candidate
            for cand in Candidate.query.all():
                total_final = total_final + 1
                res = get_numbers(str(cand.exp_years))
                if res:
                    sort_res = sorted(res)
                    years = float(sort_res[-1])
                else:
                    years = 0
                #print(cand.filename + " " + str(years))

                if int(min_expyear) <= years and years <= int(max_expyear):
                    t = 0
                    for sk in skill:
                        if sk == '':
                            t = t + 1
                    if t == len(skill):
                        if check_any(cand, any_key_list) == 1 and check_all(
                                cand, all_key_list) == 1:
                            filter_list.append(cand)
                            total = total + 1
                    else:
                        if str(skill_cond) == "0" and str(
                                skill_iter) == "None":
                            k = 0
                            if cand.skills:
                                text = str(cand.complete_resume)
                            else:
                                text = str(cand.skills)
                            freqdist = nltk.FreqDist(text.lower().split())
                            for sk in skill:
                                if sk != '':
                                    for v in freqdist.keys():
                                        if remove_number(v).find(
                                                sk.lower().strip()) >= 0:
                                            if check_any(
                                                    cand, any_key_list
                                            ) == 1 and check_all(
                                                    cand, all_key_list) == 1:
                                                filter_list.append(cand)
                                                total = total + 1
                                            keys_matched.append(sk + ", ")
                                            k = 1
                                            break
                                if k == 1:
                                    break

                        elif str(skill_cond) == "1" and str(
                                skill_iter) == "None":
                            if cand.skills:
                                text = str(cand.complete_resume)
                            else:
                                text = str(cand.skills)

                            freqdist = nltk.FreqDist(text.lower().split())
                            p = 0
                            for sk in skill:
                                if sk != '':
                                    p = p + 1
                            k = 0
                            for sk in skill:
                                if sk != '':
                                    for v in freqdist.keys():
                                        if remove_number(v).find(
                                                sk.lower().strip()) >= 0:
                                            if check_any(
                                                    cand, any_key_list
                                            ) == 1 and check_all(
                                                    cand, all_key_list) == 1:
                                                keys_matched.append(sk + ", ")
                                                k = k + 1
                            if k == p:
                                filter_list.append(cand)
                                total = total + 1

                        elif str(skill_cond) == "0" and str(skill_iter) == "1":
                            text = str(cand.complete_resume)
                            freqdist = nltk.FreqDist(text.lower().split())
                            k = 0
                            for sk in skill:
                                if sk != '':
                                    for v in freqdist.keys():
                                        if remove_number(v).find(
                                                sk.lower().strip()) >= 0:
                                            if check_any(
                                                    cand, any_key_list
                                            ) == 1 and check_all(
                                                    cand, all_key_list) == 1:
                                                filter_list.append(cand)
                                                total = total + 1
                                                keys_matched.append(sk + ", ")
                                                k = 1
                                                break
                                if k == 1:
                                    break

                        elif str(skill_cond) == "1" and str(skill_iter) == "1":
                            text = str(cand.complete_resume)
                            freqdist = nltk.FreqDist(text.lower().split())
                            p = 0
                            for sk in skill:
                                if sk != '':
                                    p = p + 1
                            k = 0
                            for sk in skill:
                                if sk != '':
                                    for v in freqdist.keys():
                                        if remove_number(v).find(
                                                sk.lower().strip()) >= 0:
                                            if check_any(
                                                    cand, any_key_list
                                            ) == 1 and check_all(
                                                    cand, all_key_list) == 1:
                                                k = k + 1
                                                keys_matched.append(sk + ", ")
                            if k == p:
                                filter_list.append(cand)
                                total = total + 1

            set_keys = set(keys_matched)

            exp_matched = str(mini) + " , " + str(maxi)
            list_set_keys = list(set_keys)
            keywords_list = []
            if any_key_list != ['']:
                keywords_list = any_key_list
            if all_key_list != ['']:
                [keywords_list.append(val) for val in all_key_list]
            print(keywords_list)
            keywords_matched.append(" | ".join(list(set(keywords_list))))
            p = 0
            for sk in skill:
                if sk == '':
                    p = p + 1
            if p == len(skill):
                val = " [ ] "
            else:
                val = ""
            if len(filter_list) == 0:
                empty = "NO MATCHES FOUND"
                filter_link = []
                return render_template('result.html',
                                       result=filter_list,
                                       skills=val + " ".join(list_set_keys),
                                       exp=" " + exp_matched + " ",
                                       key=" ".join(keywords_matched),
                                       items=len(filter_list),
                                       count=str(total) + "/" +
                                       str(total_final),
                                       empty=empty,
                                       url=filter_link,
                                       all="",
                                       any="",
                                       from_search=1)
            else:
                filter_link = []
                for cand in filter_list:
                    url_link = cand.resume
                    filter_link.append(url_link.split("/")[-1])
                result_list = rank_resume(filter_list, skill, all_key_list,
                                          any_key_list)
                return render_template('result.html',
                                       result=result_list,
                                       skills=val + " ".join(list_set_keys),
                                       exp=" " + exp_matched + " ",
                                       key=" ".join(keywords_matched),
                                       items=len(filter_list),
                                       count=str(total) + "/" +
                                       str(total_final),
                                       url=filter_link,
                                       all="",
                                       any="",
                                       from_search=1)
    else:
        empty = "NO MATCHES FOUND"
        return render_template('result.html',
                               empty_reload=empty,
                               all="",
                               any="",
                               from_search=1)
Esempio n. 10
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])
Esempio n. 11
0
def generate_bridges(bridge, components):
    if bridge is None:
        bridge = [(0, 0)]

    cur = bridge[-1][1]

    bridges = []

    for b in components[cur]:
        if not ((cur, b) in bridge or (b, cur) in bridge):
            new_bridge = bridge + [(cur, b)]
            bridges.append(new_bridge)
            bridges.extend(generate_bridges(new_bridge, components))

    return bridges


for line in puzzle_input:
    x, y = get_numbers(line)

    components[x].add(y)
    components[y].add(x)

bridges = generate_bridges(None, components)
bridge_lengths = defaultdict(list)
for bridge in bridges:
    bridge_lengths[len(bridge)].append(sum(sum(n) for n in bridge))

print('Part 1:', max(sum(sum(n) for n in bridge) for bridge in bridges))
print('Part 2:', max(bridge_lengths[max(bridge_lengths)]))
Esempio n. 12
0
    r = 0
    # the risk of a given rctangle is the sum of the numerical region types
    # within that rectangle
    for y in range(ymax + 1):
        for x in range(xmax + 1):
            r += region_type(x, y)
    return r


def is_valid(p):
    return p[0] >= 0 and p[1] >= 0


puzzle_input = load_input('input.txt')

depth = get_numbers(puzzle_input[0])[0]
targetX, targetY = get_numbers(puzzle_input[1])

# this is a (rough) upper bound for the maximum length of the shortest path to the target point
maxTime = 8 * targetX + 8 * targetY

print('Part 1:', risk(targetX, targetY))

# PART 2
print('Computing geologic index...')
gi = {}
# we precompute some geologic indices to overcome the recursion limit of python
for x in range(1000):
    for y in range(1000):
        gi[(x, y)] = geologic_index(x, y)
print('done')
Esempio n. 13
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. 14
0
    return s


noded = {}
puzzle_input = load_input('puzzle_inputs/Day7.txt')
g = Graph()

programs = set()
targets = set()

# parse puzzle input into a graph
for line in puzzle_input:
    program_name = line.split()[0]
    programs.add(program_name)
    weight = get_numbers(line)[0]
    n = get_or_create_node(program_name, weight)

    if '-> ' not in line:
        continue

    sline = line.split('-> ')[1].split(', ')
    for p in sline:
        child_node = get_or_create_node(p)
        e = Edge(n,child_node)
        g.add_edge(e)

        targets.add(p)


# start at the bottom until we find the first node that isn't misbalanced
Esempio n. 15
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. 16
0

@memoize
def get_or_create_node(n):
    node = GraphNode(n)
    nodes.add(node)
    return node


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

nodes = set()
g = Graph()

for line in puzzle_input:
    pg = get_numbers(line)
    src = pg[0]
    targets = pg[1:]

    src_node = get_or_create_node(src)

    for target in targets:
        target_node = get_or_create_node(target)
        g.add_edge_by_node(src_node, target_node)

groups = 0

while True:
    current_parent = nodes.pop()
    network = set([current_parent])
    process = set([current_parent])
Esempio n. 17
0
2637	136	3222	591	2593	1982	4506	195	4396	3741	2373	157	4533	3864	4159	142
1049	1163	1128	193	1008	142	169	168	165	310	1054	104	1100	761	406	173
200	53	222	227	218	51	188	45	98	194	189	42	50	105	46	176
299	2521	216	2080	2068	2681	2376	220	1339	244	605	1598	2161	822	387	268
1043	1409	637	1560	970	69	832	87	78	1391	1558	75	1643	655	1398	1193
90	649	858	2496	1555	2618	2302	119	2675	131	1816	2356	2480	603	65	128
2461	5099	168	4468	5371	2076	223	1178	194	5639	890	5575	1258	5591	6125	226
204	205	2797	2452	2568	2777	1542	1586	241	836	3202	2495	197	2960	240	2880
560	96	336	627	546	241	191	94	368	528	298	78	76	123	240	563
818	973	1422	244	1263	200	1220	208	1143	627	609	274	130	961	685	1318
1680	1174	1803	169	450	134	3799	161	2101	3675	133	4117	3574	4328	3630	4186
1870	3494	837	115	1864	3626	24	116	2548	1225	3545	676	128	1869	3161	109
890	53	778	68	65	784	261	682	563	781	360	382	790	313	785	71
125	454	110	103	615	141	562	199	340	80	500	473	221	573	108	536
1311	64	77	1328	1344	1248	1522	51	978	1535	1142	390	81	409	68	352""".split(
    "\n")

checksum = 0
for line in puzzle_input:
    line_numbers = get_numbers(line)

    for q in line_numbers:
        for p in line_numbers:
            if p <= q:
                continue
            # ok, so p >= q
            if (p % q == 0):
                checksum += p // q

print(checksum)
    for f in glob.glob(folder):
        if "chord" in f:
            loads = []
            for line in fileinput.input(f+"/control.queries"):
                if "loadFreqs" in line:
                    loads.append(line)
            if len(loads) < 1:
                print "coudln't find loads for " + f
                continue
            loads_d = []
            for i in loads:
                loads_d.append(get_num_dict(i))

            chord_loads.append(get_50_percent(loads_d[0]))

            x_values1.append(next(get_numbers(f)))

    for f in glob.glob(folder):
        if "best" in f:
            loads = []
            for line in fileinput.input(f+"/control.queries"):
                if "loadFreqs" in line:
                    loads.append(line)
            if len(loads) < 1:
                print "coudln't find loads for " + f
                continue
            loads_d = []
            for i in loads:
                loads_d.append(get_num_dict(i))

            best_loads.append(get_50_percent(loads_d[0]))
Esempio n. 19
0
        elif move[0] == 's':
            x = move[1]
            new_state = new_state[-x:] + new_state[:-x]

    return new_state


puzzle_input = load_input("puzzle_inputs/Day16.txt")[0].split(",")

dance = []

for move in puzzle_input:
    move_type = move[0]

    if move_type == 's':
        spin_by = get_numbers(move)[0]
        dance.append(('s', spin_by))
    elif move_type == 'x':
        v1, v2 = get_numbers(move)
        dance.append(('x', v1, v2))
    else:
        z = move[1:].replace('/', '')
        dance.append(('p', z[0], z[1]))

state = [letter(q) for q in range(16)]
state = perform_dance(state)
print('Part 1:', ''.join(state))

# For part 2, we do some simple repetition detection
state = [letter(q) for q in range(16)]
visited = {}
Esempio n. 20
0
    wealth = banks[max_bank]
    banks[max_bank] = 0

    current_bank = (max_bank + 1) % len(banks)

    while wealth > 0:
        banks[current_bank] += 1
        current_bank = (current_bank + 1) % len(banks)
        wealth -= 1


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

banks = {}
for (k, line) in enumerate(get_numbers(puzzle_input[0])):
    banks[k] = int(line)

bank_state = tuple(banks.values())
visited = set()
seen_at = {}
steps = 0

while bank_state not in visited:
    seen_at[bank_state] = steps
    visited.add(bank_state)
    redistribute_blocks()
    bank_state = tuple(banks.values())
    steps += 1

print('Part 1:', len(visited))
Esempio n. 21
0
from utils import load_input, get_numbers
from elfcode import *

puzzle_input = load_input('input.txt')
og_instruction_pointer = get_numbers(puzzle_input[0])[0]
instruction_pointer = 0

instructions = []

for (k, line) in enumerate(puzzle_input[1:]):
    l = line.split(" ")
    instructions.append((eval(l[0]), *get_numbers(line)))

register = [0, 0, 0, 0, 0, 0]

while True:
    # write the value of the instruction pointer to the corresponding register
    register[og_instruction_pointer] = instruction_pointer

    # now do the code
    p, x, y, z = instructions[instruction_pointer]

    p(register, x, y, z)

    # now set the instruction pointer equal to the value of the corresponding register
    instruction_pointer = register[og_instruction_pointer]
    instruction_pointer += 1

    if instruction_pointer < 0 or instruction_pointer >= len(instructions):
        print('Out of range')
        break
        if to_match in f:
            loads = []
            for line in fileinput.input(f+"/control.queries"):
                if "loadFreqs" in line:
                    loads.append(line)
            if len(loads) < 2:
                print "coudln't find loads for " + f
                continue
            loads_d = []
            for i in loads:
                loads_d.append(get_num_dict(i))

            chord_loads.append(get_50_percent(loads_d[0]))
            vserver_loads.append(get_50_percent(loads_d[1]))

            x_values.append(next(get_numbers(f)))

    plt.figure().set_size_inches(6.5,5)
    plt.xlabel("#Nodes")
    plt.ylabel("% of nodes storing 50% of data")

    from matplotlib.ticker import EngFormatter
    formatter = EngFormatter(places=0)
    plt.gca().xaxis.set_major_formatter(formatter)

    plt.ylim(0,0.5)
    plt.xlim(0,1000000)

    out_file = "intro_lb_chord.pdf"

    d1 = prepare(x_values,chord_loads)
if __name__ == "__main__":
    import doctest
    doctest.testmod()

    folder = "../tmp/*"

    x_values1 = []
    x_values2 = []
    chord_values = []
    best_values = []
    for f in glob.glob(folder):
        if "chord" in f or "best" in f:
            print "at",f
            count = 0
            for line in fileinput.input(f+"/control.messagecost.weighted"):
                ns = get_numbers(line)
                count += list(ns)[-1]

            nsize = next(get_numbers(f))
            if "chord" in f:
                chord_values.append(count/nsize)
                x_values1.append(nsize)
            else:
                best_values.append(count/nsize)
                x_values2.append(nsize)


    plt.figure().set_size_inches(6.5,5)
    plt.xlabel("#Nodes")
    plt.ylabel("Per-node Replication Maintenance Cost (KB)")
Esempio n. 24
0
    return r

if __name__ == "__main__":
    import doctest
    doctest.testmod()

    f = argv[1]

    d = dict()
    for i in ["J","K","D","M"]:
        d[i] = {'x':[],'y':[]}
    s = {'x':[],'y':[]}

    for line in fileinput.input(f+"/out.execution"):
        if line.startswith("J") or line.startswith("K") or line.startswith("D") or line.startswith("M"):
            t,n,k = get_numbers(line)
            a = 27000
            if t < a:
                continue

            d[line[:1]]['x'].append(t)
            d[line[:1]]['y'].append(k)
            s['x'].append(t)
            s['y'].append(n)

    for i in d:
        print "sum for",i,sum(d[i]['y'])/1000,"x1000"
    for i in d:
        print "avg for",i,sum(d[i]['y'])/float(len(d[i]['y']))
    for i in d:
        print "std for",i,np.std(d[i]['y'])
Esempio n. 25
0
def main():
    # get the list of points
    points = [get_numbers(q) for q in load_input('input.txt')]

    print('Part 1:', part1(points))
    print('Part 2:', part2(points))