Exemple #1
0
import datetime
import argparse
import cProfile, pstats, StringIO
from file_importer import FileImporter
from metric_calculator import MetricCalculator

parser = argparse.ArgumentParser(description='Read a Tab-separated Graph Datafile and start Calculation of Metrics and Statistics as configured in config.py')

parser.add_argument('filename', metavar='filename', type=str,
                   help='the name of the data file containing tab separated node ids')

parser.add_argument('--profiling',dest='profiling',action='store_true', help='enable runtime profiling into profiling.txt file')

args = parser.parse_args()

if args.profiling:
  pr = cProfile.Profile()
  s = StringIO.StringIO()
  timestamp = str(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
  outfile = open('profiling_output_'+timestamp+'.txt', 'w')
  pr.enable()

fi = FileImporter(args.filename)
graph = fi.read()
mc = MetricCalculator(graph)
mc.start()

if args.profiling:
  ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
  ps.print_stats()
  outfile.write(s.getvalue())
Exemple #2
0
from file_importer import FileImporter

def spin(ary, ind): 
    ind = len(ary) - ind
    return ary[ind:] + ary[:ind]

def exchange(ary, pos1, pos2):
    tmp = ary[pos1]
    ary[pos1] = ary[pos2]
    ary[pos2] = tmp
    return ary

def partner(ary, char1, char2):
    pos1, pos2 = ary.index(char1), ary.index(char2)
    return exchange(ary, pos1, pos2)

progs = [chr(i) for i in range(97, 113)]

inp = FileImporter.get_input("/../input/16.txt").split(",")

for i in inp:
    x = i.split("/")
    if len(x) == 1:
        progs = spin(progs, int(x[0][1:]))
    elif x[0][0] == "x":
        progs = exchange(progs, int(x[0][1:]), int(x[1]))
    elif x[0][0] == "p":
        progs = partner(progs, x[0][1], x[1])

print("".join(progs))
Exemple #3
0
    return False


def get_hash(salt, ind, cache):
    hashed = ""
    if ind not in cache:
        to_hash = salt + str(ind)
        hashed = md5(to_hash.encode('utf-8')).hexdigest()
        cache[ind] = hashed
    else:
        hashed = cache[ind]
    return hashed


# Get input
inp = FileImporter.get_input("/../input/14a.txt").strip()

index = 0
keys = 0

hash_cache = {}  # Couldn't wait to use this one.

while True:
    hashed = get_hash(inp, index, hash_cache)

    first_repeated = get_first_repeated(hashed, 3)
    if first_repeated:

        for i in range(index + 1, index + 1001):
            hashed = get_hash(inp, i, hash_cache)
            if has_repeated_sequence(hashed, first_repeated, 5):
Exemple #4
0
from file_importer import FileImporter
from enum import Enum

inp = [list(map(int, i.split(": "))) for i in FileImporter.get_input("/../input/13.txt").split('\n')]

class Scanner:
    def __init__(self, rang):
        self.rang = rang

    def get_pos(self, ps):
        indRang = self.rang - 1
        return abs(indRang - ((ps + indRang) % (indRang*2)))

delay = 0
scanners = [None for x in range(inp[-1][0] + 1)] 
for i in inp:
    scanners[i[0]] = Scanner(i[1])                                        

severity = 0
found = False
for i in range(len(scanners)):
    if scanners[i] is None:
        continue

    pos = scanners[i].get_pos(i)
    if pos == 0:
        severity += i * scanners[i].rang

print(severity)
Exemple #5
0
    for sequence in sequences:
        abas.append(get_aba(sequence))
    return filter(None, abas)


def supports_ssl(abas, babs):
    for i in abas:
        for j in babs:
            if is_bab_of(i, j):
                return True
    return False


# Get input
inp = [
    i.strip() for i in FileImporter.get_input("/../input/7a.txt").split("\n")
]

count_support_SSL = 0
for ip in inp:
    without_hypernets = filter(None, re.split("\[\w*\]", ip))

    abas = []
    for sequence in without_hypernets:
        abas += get_abas(sequence)

    if len(abas) == 0:
        continue

    hypernets = re.findall("\[\w*\]", ip)
    babs = []
Exemple #6
0
from file_importer import FileImporter


def add_tup(t1, t2):
    return (t1[0] + t2[0], t1[1] + t2[1])


def negate_touple(t1):
    return (-t1[0], -t1[1])


# Row, Column Deltas
UP, DOWN, RIGHT, LEFT = (-1, 0), (1, 0), (0, 1), (0, -1)

inp = [i for i in FileImporter.get_input("/../input/19.txt").split('\n')]

current = (0, inp[0].index('|'))
direction = DOWN
letters = []

steps = 1
while True:
    nxt = add_tup(current, direction)
    char = inp[nxt[0]][nxt[1]]
    if char == '+':
        for i in (set([UP, DOWN, RIGHT, LEFT]) -
                  set([direction, negate_touple(direction)])):
            turned_coord = add_tup(nxt, i)
            if inp[turned_coord[0]][turned_coord[1]] in '|-':
                direction = i
                break
Exemple #7
0
from file_importer import FileImporter
from queue import Queue

# Dictionary of program ID to list of connecting program IDs
inp = {int(i.split(" <-> ")[0]): list(map(int, i.split(" <-> ")[1].split(', '))) for i in FileImporter.get_input("/../input/12.txt").split('\n')}

q = Queue()
contained = set([0]) # Start with 0
q.put(inp[0])

while not q.empty():
    for program in q.get():
        if not program in contained: 
            contained.add(program)
            q.put(inp[program])

print(len(contained))
Exemple #8
0
from file_importer import FileImporter
from queue import Queue
import sys

# Get input
fav_number = int(FileImporter.get_input("/../input/13a.txt"))


def check_position(x, y):
    global fav_number
    if x < 0 or y < 0:
        return False
    binary_rep = bin((x * x + 3 * x + 2 * x * y + y + y * y) + fav_number)
    return True if binary_rep.count("1") % 2 == 0 else False


start = (1, 1, 0)
end = (31, 39)
visited = []
q = Queue()
q.put(start)

while not q.empty():
    position = q.get()
    visited.append((position[0], position[1]))

    for i in range(-1, 2):
        for j in range(-1, 2):
            x, y, dist = position[0] + i, position[1] + j, position[2] + 1

            if abs(i) != abs(j):
Exemple #9
0
from file_importer import FileImporter


def reverse_length(_list, currentPos, length):
    reverse = list(
        reversed([
            _list[i % len(_list)]
            for i in range(currentPos, currentPos + length)
        ]))
    for i in reverse:
        _list[currentPos % len(_list)] = i
        currentPos += 1
    return _list


lengths = list(map(int, FileImporter.get_input("/../input/10.txt").split(',')))
nums = list(range(256))
currentPos = skipSize = 0

for length in lengths:
    nums = reverse_length(nums, currentPos, length)
    currentPos += length + skipSize
    currentPos %= 256
    skipSize += 1

print(nums[0] * nums[1])
Exemple #10
0
from file_importer import FileImporter

inp = [j for j in [i.split(' -> ') for i in FileImporter.get_input("/../input/7.txt").split("\n")] if len(j) > 1]

left, right = set(), set()
for i in inp:
    left.add(i[0].split()[0].strip())
    for j in i[1].split(', '):
        right.add(j.strip())

print(list((left - right))[0])
Exemple #11
0
from file_importer import FileImporter

inp = [
    i.split(" ") for i in FileImporter.get_input("/../input/4.txt").split("\n")
]

print(
    len([
        l for l in inp
        if len(set(["".join(sorted(i))
                    for i in l])) == len(["".join(sorted(i)) for i in l])
    ]))
Exemple #12
0
import re

def get_dragon_curve(a):
    b = reversed(a)
    b = ''.join('1' if x == '0' else '0' for x in b)
    return a + "0" + b

def get_checksum(inp):
    final = ""
    pairs = re.findall("..", inp)
    for pair in pairs:
        if pair[0] == pair[1]:
            final += "1"
        else:
            final += "0"
    if len(final) % 2 == 0:
        return get_checksum(final)
    return final

# Get input
for_checksum =  FileImporter.get_input("/../input/16a.txt").strip()

disk_length = 272

# Get proper input to compute checksum
while len(for_checksum) < disk_length:
    for_checksum = get_dragon_curve(for_checksum)
for_checksum = for_checksum[:disk_length]

print(get_checksum(for_checksum))
Exemple #13
0
        global cursor

        # 0 is always rule 1 and 1 is always rule 2
        rule = self.rule1 if tape[cursor] == 0 else self.rule2

        # step 1 - write new val
        tape[cursor] = rule.new_val

        # step 2 - move cursor
        cursor += rule.new_dir

        # step 3 - update state
        state = rule.new_state


inp = FileImporter.get_input("/../input/25.txt").split('\n')
tape = defaultdict(lambda: 0)
state = 'A'
cursor = 0

states = {
    'A': State(tape, Rule(1, 1, 'B'), Rule(0, -1, 'F')),
    'B': State(tape, Rule(0, 1, 'C'), Rule(0, 1, 'D')),
    'C': State(tape, Rule(1, -1, 'D'), Rule(1, 1, 'E')),
    'D': State(tape, Rule(0, -1, 'E'), Rule(0, -1, 'D')),
    'E': State(tape, Rule(0, 1, 'A'), Rule(1, 1, 'C')),
    'F': State(tape, Rule(1, -1, 'A'), Rule(1, 1, 'A'))
}

for i in range(12794428):
    c_state = states[state]
Exemple #14
0
from file_importer import FileImporter
from collections import OrderedDict

# Get input
inp = int(FileImporter.get_input("/../input/19a.txt").strip())

# List of elf ID's
elves = [i for i in range(1, inp + 1)]

while len(elves) != 1:
    size = len(elves)
    # delete all evens
    del elves[1::2]
    # if list size was odd and we haven't accounted for final item, append it to front and restart :)
    if size % 2 != 0:
        elves.insert(0, elves.pop())

print(elves[0])
Exemple #15
0
from file_importer import FileImporter
from collections import defaultdict

inp = FileImporter.get_input("/../input/11.txt").split(',')
dic = defaultdict(lambda: 0)

max = 0
for i in inp:
    dic[i] += 1
    xabs = abs((dic["ne"] + dic["se"]) - (dic["nw"] + dic["sw"]))
    yabs = abs((dic["n"] + dic["nw"]) - (dic["s"] + dic["se"]))
    zabs = abs((dic["s"] + dic["sw"]) - (dic["n"] + dic["ne"]))
    dist = int((xabs + zabs + yabs) / 2)
    if dist > max:
        max = dist
print(max)
Exemple #16
0
from file_importer import FileImporter

steps = int(FileImporter.get_input("/../input/17.txt"))
currentPos = 0
buffer = [0]
newVal = 1

for i in range(2017):
    currentPos = ((currentPos + steps) % len(buffer)) + 1
    buffer.insert(currentPos, newVal)
    newVal += 1

print(buffer[currentPos + 1])
Exemple #17
0
from file_importer import FileImporter
import math
from collections import defaultdict


def add_tuple(t1, t2):
    return (t1[0] + t2[0], t1[1] + t2[1])


def get_key(x, y):
    return str(x) + ',' + str(y)


inp = [list(i) for i in FileImporter.get_input("/../input/22.txt").split("\n")]

grid_dic = defaultdict(lambda: '.')

for i in range(len(inp)):
    for j in range(len(inp)):
        grid_dic[get_key(i, j)] = inp[i][j]

# Map of direction number to the vector you'll travel
directions = {
    0: (0, 1),  # Right
    1: (-1, 0),  # Up
    2: (0, -1),  # Left
    3: (1, 0),  # Down
}

# Initial position is middle of grid, direction is up. Grid is a square
c_pos = (math.floor(len(inp) / 2), math.floor(len(inp) / 2))
Exemple #18
0
from file_importer import FileImporter

class Gen:
    def __init__(self, prevVal: int, factor, divis, mod):
        self.prevVal = prevVal
        self.factor = factor
        self.divis = divis
        self.mod = mod
    def next(self): 
        self.prevVal = (self.prevVal * self.factor) % self.divis
        if not self.prevVal % self.mod == 0: return self.next()
        return self.prevVal

inp = FileImporter.get_input("/../input/15.txt").split("\n")
FACTOR_A, FACTOR_B, DIVISOR = 16807, 48271, 2147483647

gen_a = Gen(int(inp[0].split(" ")[-1]), FACTOR_A, DIVISOR, 4)
gen_b = Gen(int(inp[1].split(" ")[-1]), FACTOR_B, DIVISOR, 8)

print(sum(gen_a.next() & 0xffff == gen_b.next() & 0xffff for i in range(5000000)))
Exemple #19
0
from file_importer import FileImporter

# Get input
inp = [
    list(map(int, y.split("-"))) for y in [
        x.strip()
        for x in FileImporter.get_input("/../input/20a.txt").split("\n")
    ]
]
inp = sorted(inp, key=lambda x: x[0])

max0, max1 = inp[0][0], inp[0][1]
allowed = 0
for i in inp:
    if i[0] > max0:
        max0 = i[0]

    if max0 > max1 + 1:
        allowed += 1

    if i[1] > max1:
        max1 = i[1]

print(allowed)
Exemple #20
0
from file_importer import FileImporter

inp = [
    list(map(int, i.split("\t")))
    for i in FileImporter.get_input("/../input/2.txt").split('\n')
]

sum = 0
for row in inp:
    for num in row:
        divs = list(row)
        divs.remove(num)
        for otherNum in divs:
            if (num % otherNum == 0):
                sum += num // otherNum
print(sum)
Exemple #21
0
from file_importer import FileImporter

# Get Input
inp = [i.strip().split("  ") for i in FileImporter.get_input("/../input/3a.txt").split("\n")]

possible = 0

for line in inp:
    line = sorted([int(i.strip()) for i in list(filter(None, line))])

    if line[0] + line[1] > line[2]:
        possible += 1
        
print(possible)
Exemple #22
0
from file_importer import FileImporter

def get_name(file):
    return file.split("-", 1)[1]

FILESYSTEM, SIZE, USED, AVAIL, USEP = 0, 1, 2, 3, 4
inp =  [x.strip().split() for x in FileImporter.get_input("/../input/22a.txt").split("\n")][:]

pairs = 0
for a in range(len(inp)):
    node_a = inp[a]
    for b in range(a+1, len(inp)):
        node_b = inp[b]

        if int(node_a[USED][:-1]) != 0 and int(node_a[USED][:-1]) < int(node_b[AVAIL][:-1]):
            pairs += 1
            break

        if int(node_b[USED][:-1]) != 0 and int(node_b[USED][:-1]) < int(node_a[AVAIL][:-1]):
            pairs += 1

print(pairs)
            
Exemple #23
0
from file_importer import FileImporter

inp = FileImporter.get_input("/../input/1.txt")

steps = len(inp) // 2
print(
    sum([
        int(inp[i]) for i in range(len(inp))
        if inp[i] == inp[(i + steps) % len(inp)]
    ]))
Exemple #24
0
from file_importer import FileImporter

inp = list(map(int, FileImporter.get_input("/../input/6.txt").split()))


def max_bank_ind(banks):
    max = 0
    for i in range(len(banks)):
        if banks[i] > banks[max]:
            max = i
    return max


def realloc(banks, bankInd):
    blocks, banks[bankInd] = banks[bankInd], 0
    while blocks > 0:
        bankInd += 1
        banks[bankInd % len(banks)] += 1
        blocks -= 1


states, count = [], 0
while inp not in states:
    states.append(inp[:])
    maxInd = max_bank_ind(inp)
    realloc(inp, maxInd)
    count += 1

print(count)
Exemple #25
0
from file_importer import FileImporter

# Get input
inp = [
    i.split(" ")
    for i in FileImporter.get_input("/../input/12a.txt").split("\n")
]
registers = {"a": 0, "b": 0, "c": 0, "d": 0}

i = 0
while i < len(inp):
    instr = inp[i]
    if instr[0] == "cpy":
        if instr[1].isdigit():
            registers[instr[2]] = int(instr[1])
        else:
            registers[instr[2]] = registers[instr[1]]
    elif instr[0] == "inc":
        registers[instr[1]] += 1
    elif instr[0] == "dec":
        registers[instr[1]] -= 1

    if instr[0] == "jnz":
        val = 0
        if instr[1].isdigit():
            val = int(instr[1])
        else:
            val = registers[instr[1]]
        if val != 0:
            i += int(instr[2])
            continue
Exemple #26
0
from file_importer import FileImporter
from operator import xor
from functools import reduce

def reverse_length(_list, currentPos, length): 
    reverse = list(reversed([_list[i % len(_list)] for i in range(currentPos, currentPos + length)]))
    for i in reverse: 
        _list[currentPos % len(_list)] = i
        currentPos += 1
    return _list

lengths = [ord(i) for i in FileImporter.get_input("/../input/10.txt")] + [17, 31, 73, 47, 23] # Get ascii for each char, add 
nums = list(range(256))                                                                       # the problem-defined sequence
currentPos = skipSize = 0

# Run 64 rounds
for i in range(64):
    for length in lengths:
        nums = reverse_length(nums, currentPos, length)
        currentPos += length + skipSize; currentPos %= 256
        skipSize += 1

# Calculate dense hash - 16 blocks
denseHash = []
for i in range(16):
    hashVal = reduce(xor, [i for i in nums[i * 16:i * 16 + 16]])
    denseHash.append(hashVal)

# Function to add leading 0 if necessary
ensurelen = lambda x: '0' + x if len(x) == 1 else x