def p1(): data = {} state = {} direction = {} for line in read_lines(13): idx, depth = line.split(': ') data[int(idx)] = int(depth) state[int(idx)] = 0 direction[int(idx)] = 1 keys = data.keys() m = max(keys) for x in range(m + 1): if x not in data: data[x] = 0 state[x] = 0 idx = -1 severity = [] # print data for x in range(m + 1): idx += 1 # print idx, state if data[x] > 0 and state[x] == 0: severity.append(x) for d, r in state.items(): if data[d] > 0: state[d] += (1 * direction[d]) if state[d] >= data[d]: direction[d] = -1 state[d] -= 2 if state[d] < 0: direction[d] = 1 state[d] += 2 print sum([d * x for d, x in data.items() if d in severity])
def p2(): groups = 0 for line in read_lines(9, 1): total, removed = find_groups(line) groups += removed print groups
def p2(): # Distance: # http://althenia.net/svn/stackoverflow/hexgrid.png?usemime=1&rev=3 # https://stackoverflow.com/questions/5084801/manhattan-distance-between-tiles-in-a-hexagonal-grid # 1567 for line in read_lines(11): solve2(line)
def p2(): for line in read_lines(1, 2): l = len(line) s = l / 2 sum = 0 for i in xrange(l - s): if line[i] == line[i + s]: sum += (2 * int(line[i])) print sum
def read_internal_cpds(fn): f = open(fn) cpds = {} for u, v, p_add, p_del in common.read_lines(f): mp = MutationParameter(float(p_add), float(p_del)) if u not in cpds: cpds[u] = {} cpds[u][v] = mp return cpds
def p1(): for line in read_lines(1, 1): data = line + line[0] sum = 0 for i in xrange(len(data)): if i > 0: if data[i - 1] == data[i]: sum += int(data[i]) print sum
def p1(): programs = {} for line in read_lines(12, 2): program, childs = line.split('<->') childs = childs.split(',') programs[program.strip()] = [c.strip() for c in childs] found = [] for program, childs in programs.items(): traversed = [] ok = traverse_to_zero(programs, program, traversed) if ok: found.append(program) print len(found)
def read_evidence(f): evidence = {} for node, reaction, blast, gtg in common.read_lines(f): if blast != "?": blast = float(blast) else: blast = 0.0 if gtg != "?": gtg = float(gtg) else: gtg = 0.0 if reaction not in evidence: evidence[reaction] = {} evidence[reaction][node] = {"BLAST" : blast, "GTG" : gtg} return evidence
def read_evidence(f): evidence = {} for node, reaction, blast, gtg in common.read_lines(f): if blast != "?": blast = float(blast) else: blast = 0.0 if gtg != "?": gtg = float(gtg) else: gtg = 0.0 if reaction not in evidence: evidence[reaction] = {} evidence[reaction][node] = {"BLAST": blast, "GTG": gtg} return evidence
def p2(): particles = [] for line in read_lines(20): data = line.split(', ') p, p_data = data[0].split('=') p_data = [int(x) for x in p_data[1:][:-1].split(',')] v, v_data = data[1].split('=') v_data = [int(x) for x in v_data[1:][:-1].split(',')] a, a_data = data[2].split('=') a_data = [int(x) for x in a_data[1:][:-1].split(',')] particles.append({ 'p': p_data, 'v': v_data, 'a': a_data, }) for x in xrange(10**4): if x % 1000 == 0: print x collide_zone = {} for idx in xrange(len(particles)): particle = particles[idx] # Increase the X velocity by the X acceleration. # Increase the Y velocity by the Y acceleration. # Increase the Z velocity by the Z acceleration. # Increase the X position by the X velocity. # Increase the Y position by the Y velocity. # Increase the Z position by the Z velocity. particle['v'][0] += particle['a'][0] particle['v'][1] += particle['a'][1] particle['v'][2] += particle['a'][2] particle['p'][0] += particle['v'][0] particle['p'][1] += particle['v'][1] particle['p'][2] += particle['v'][2] key = '%d:%d:%d' % (particle['p'][0], particle['p'][1], particle['p'][2]) if not collide_zone.get(key): collide_zone[key] = [] collide_zone[key].append(idx) to_delete = [] for k,v in collide_zone.items(): if len(v) > 1: for idx in v: to_delete.append(idx) new_particles = [particles[idx] for idx in xrange(len(particles)) if idx not in to_delete] particles = new_particles print len(particles)
def p2(): children = {} parents = {} weight = {} for line in read_lines(7): struct = line.split('->') x = struct[0].split('(')[0].strip() weight[x] = int(struct[0].split('(')[1].split(')')[0].strip()) children[x] = [] if len(struct) > 1: for s in struct[1].split(','): parents[s.strip()] = x children[x].append(s.strip()) root = None node, parent = parents.items()[0] while True: root = parent if not parent in parents: break node = parent parent = parents[parent] def set_weight(x): ch = children[x] if not len(children): return weight[x] ws = {} for c in ch: ws[c] = set_weight(c) vals = ws.values() if len(vals) > 0: mi = min(vals) ma = max(vals) if mi != ma: diff = ma - mi for a, b in ws.items(): if b == ma: print a, weight[a], diff, weight[a] - diff return weight[x] + sum(vals) set_weight(root)
def p1(): data = {} for line in read_lines(7): struct = line.split('->') x = struct[0].split('(')[0].strip() has_children = len(struct) > 1 if has_children: for s in struct[1].split(','): data[s.strip()] = x bottom = None node, parent = data.items()[0] while True: bottom = parent if not parent in data: break node = parent parent = data[parent] print bottom
def p2(): programs = {} for line in read_lines(12, 2): program, childs = line.split('<->') childs = childs.split(',') programs[program.strip()] = [c.strip() for c in childs] groups = 0 # Iterate all programs for program, childs in programs.items(): traversed = [] # Check programs not already traversed if program in programs: # Find all subprocesses for the programs traverse(programs, program, traversed) if len(traversed) > 0: groups += 1 for t in traversed: if t in programs: # Remove all traversed programs from the initial queue del programs[t] print groups
def p1(): particles = [] for line in read_lines(20): data = line.split(', ') p, p_data = data[0].split('=') p_data = [int(x) for x in p_data[1:][:-1].split(',')] v, v_data = data[1].split('=') v_data = [int(x) for x in v_data[1:][:-1].split(',')] a, a_data = data[2].split('=') a_data = [int(x) for x in a_data[1:][:-1].split(',')] particles.append({ 'p': p_data, 'v': v_data, 'a': a_data, }) for x in xrange(10**4): if x % 1000 == 0: print x for idx in xrange(len(particles)): particle = particles[idx] particle['v'][0] += particle['a'][0] particle['v'][1] += particle['a'][1] particle['v'][2] += particle['a'][2] particle['p'][0] += particle['v'][0] particle['p'][1] += particle['v'][1] particle['p'][2] += particle['v'][2] closest_idx = 0 closest_distance = 10**50 for idx in xrange(len(particles)): particle = particles[idx] distance = abs(particle['p'][0]) + abs(particle['p'][1]) + abs(particle['p'][2]) if distance < closest_distance: closest_idx = idx closest_distance = distance print closest_idx, closest_distance
def fct_nop(i): global ip ip += 1 def fct_acc(i): global acc, ip acc += i ip += 1 def fct_jmp(i): global ip ip += i execute = {"nop": fct_nop, "acc": fct_acc, "jmp": fct_jmp} lines = common.read_lines("data.txt") visited = set() while True: if ip in visited: break visited.add(ip) tokens = lines[ip].split(" ") execute[tokens[0]](int(tokens[1])) print(acc)
def p2(): # START = time.time() # data = open("data/p13.txt", "r") # rows = data.read().strip().split("\n") # valDict = dict() # for row in rows: # rowS = row.split(" ") # valDict[int(rowS[0][:-1])] = int(rowS[-1]) # caught = False # for delay in xrange(10, 10**7): # caught = False # print 'DELAY', delay # for i in valDict.keys(): # print i, (i+delay), (2* valDict[i] - 2), (i+delay) % (2* valDict[i] - 2) == 0 # if (i+delay) % (2* valDict[i] - 2) == 0: # caught = True # break # if not caught: # print delay # break # print "Time Taken:", time.time() - START # 3946838 data = {} state = {} direction = {} for line in read_lines(13): idx, depth = line.split(': ') data[int(idx)] = int(depth) state[int(idx)] = 0 direction[int(idx)] = 1 keys = data.keys() m = max(keys) for x in range(m + 1): if x not in data: data[x] = 0 state[x] = 0 initial_data = copy.deepcopy(data) initial_state = copy.deepcopy(state) initial_direction = copy.deepcopy(direction) for i in range(10): for d in initial_state.keys(): if initial_data[d] > 0: initial_state[d] += (1 * initial_direction[d]) if initial_state[d] >= initial_data[d]: initial_direction[d] = -1 initial_state[d] -= 2 if initial_state[d] < 0: initial_direction[d] = 1 initial_state[d] += 2 for p in xrange(11, 10**7): for d in initial_state.keys(): if initial_data[d] > 0: initial_state[d] += (1 * initial_direction[d]) if initial_state[d] >= initial_data[d]: initial_direction[d] = -1 initial_state[d] -= 2 if initial_state[d] < 0: initial_direction[d] = 1 initial_state[d] += 2 data = copy.deepcopy(initial_data) state = copy.deepcopy(initial_state) direction = copy.deepcopy(initial_direction) idx = -1 severity = [] if p % 100 == 0: print p caught = False for x in xrange(m + 1): idx += 1 if data[x] > 0 and state[x] == 0: caught = True break for d in state.keys(): if data[d] > 0: state[d] += (1 * direction[d]) if state[d] >= data[d]: direction[d] = -1 state[d] -= 2 if state[d] < 0: direction[d] = 1 state[d] += 2 if not caught: break print p
#!/usr/bin/env python3 import serial from common import port, baudrate, interpret_messages, read_lines with serial.Serial(port=port, baudrate=baudrate) as ser: for msg in interpret_messages(read_lines(ser), skip_nmea=True): print(msg)
def p2(): for line in read_lines(10, 2): do_hash(line)
score = score_area(points) if score < best_score: best_score = score best_points = points seconds = i elif score >= best_score: break points = step(points) return seconds, best_points def draw_message(seconds, points): coords = {point.coord for point in points} left, top, right, bottom = bounds(coords) lines = [] for y in range(top, bottom + 1): for x in range(left, right + 1): lines.append("X" if (x, y) in coords else ".") lines.append("\n") print("".join(lines)) print(f"{seconds} seconds") draw_message(*find_message(parse(read_lines())))
assert asleep is None guard_id = int(rest[0][1:]) elif first == "falls": assert asleep is None asleep = date elif first == "wakes": index[guard_id].update(range(asleep.minute, date.minute)) asleep = None return index def strat_one(minutes): id, counts = max(minutes.items(), key=lambda x: sum(x[1].values())) minute = counts.most_common(1)[0][0] print(id, minute, id * minute) def strat_two(minutes): def extract(): for id, counts in minutes.items(): yield id, counts.most_common(1)[0] id, (minute, count) = max(extract(), key=lambda x: x[1][1]) print(id, minute, count, id * minute) data = get_minutes(sorted(read_lines())) strat_one(data) strat_two(data)
from bisect import insort_left from collections import defaultdict from networkx import DiGraph from networkx import lexicographical_topological_sort from common import read_lines def parse(lines): return DiGraph( sorted((parts[1], parts[7]) for parts in (line.split() for line in lines))) graph = parse(read_lines()) print("".join(lexicographical_topological_sort(graph))) def build(graph, workers=5, base_cost=60): base_cost -= ord("A") - 1 incomplete = set(graph.nodes) available = sorted(n for n, d in graph.in_degree if d == 0) schedule = defaultdict(list) time = 0 while incomplete: done = schedule.pop(time, ()) incomplete.difference_update(done) workers += len(done)
def runtests(file, expected_status): print "Running tests from %s" % file return [runtest(test.rstrip().split(), expected_status) for test in common.read_lines(file)]
for y, line in enumerate(lines): for x, c in enumerate(line): if c in "^>v<": carts[x, y] = Cart(x, y, c) c = "-" if c in "><" else "|" track[x, y] = c return track, carts def run(lines): track, carts = parse(lines) first_crash = False while len(carts) > 1: order = sorted(carts.values(), key=lambda c: (c.y, c.x)) for cart in order: cart.move(track, carts) if cart.crash: if not first_crash: first_crash = True print(cart) print(next(iter(carts.values()))) run(read_lines("input.txt"))
from itertools import cycle from common import read_lines data = [int(x) for x in read_lines()] print(sum(x for x in data)) seen = set() current = 0 for item in cycle(data): current += item if current in seen: print(current) break seen.add(current)
def get_options(src): xs = [x.strip() for x in common.read_lines(src) if "(* DSOLVE" in x ] ss = ' '.join([' '] + [x[9:-2] for x in xs]) xs = [x.strip() for x in ss.split(' ') if x.strip()] return xs
_extra = (False, ) * 5 def run(lines, steps=20): pots, notes = parse(lines) score = 0 delta = 0 for i in range(1, steps + 1): pots = tuple( notes.get(items, False) for items in windowed(chain(_extra, pots, _extra), 5)) offset = 3 * i new_score = sum(c * (i - offset) for i, c in enumerate(pots)) new_delta = new_score - score score = new_score if new_delta == delta: score += (steps - i) * new_delta break delta = new_delta return score print(run(read_lines("input.txt"))) print(run(read_lines("input.txt"), 50_000_000_000))
#!/usr/bin/env python import collections import os import sys sys.path.append( os.path.abspath( ".." ) ) import common current = common.read_lines( "data.txt" ) w = len( current[ 0 ] ) h = len( current ) def get_neighbours( state, x, y ): count = 0 for dx in [ -1, 0, +1 ]: for dy in [ -1, 0, +1 ]: if dx == 0 and dy == 0: continue sx = x + dx sy = y + dy if sx < 0 or sy < 0 or sx >= w or sy >= h: continue if state[ sy ][ sx ] == "#": count += 1 return count while True: state = [ [ '.' ] * w for _ in range( h ) ] for x in range( w ): for y in range( h ):
def p1(): # 810 for line in read_lines(11): solve(line)
def runtests(file, expected_status): print "Running tests from %s" % file return [ runtest(test.rstrip().split(), expected_status) for test in common.read_lines(file) ]
@classmethod def from_line(cls, line): m = cls._line_re.match(line) return cls(*[int(g) for g in m.groups()]) @property def x_range(self): return range(self.left, self.left + self.width) @property def y_range(self): return range(self.top, self.top + self.height) def __iter__(self): for x in self.x_range: for y in self.y_range: yield x, y def intact(self, point_counts): return all(point_counts[point] == 1 for point in self) data = [Claim.from_line(line) for line in read_lines()] point_counts = Counter([point for claim in data for point in claim]) print(sum(count > 1 for count in point_counts.values())) for claim in data: if claim.intact(point_counts): print(claim) break
def parse(): return [(int(x), int(y)) for x, y in (line.split(", ", 1) for line in read_lines())]
from collections import Counter from functools import lru_cache from itertools import combinations from common import read_lines data = read_lines() twos = 0 threes = 0 for item in data: counts = Counter(item).values() if 2 in counts: twos += 1 if 3 in counts: threes += 1 print(twos, threes, twos * threes) @lru_cache(len(data)) def positions(item): return set(enumerate(item)) for a, b in combinations(data, 2): diff = positions(a) ^ positions(b)