diff --git a/10/10_2.py b/10/10_2.py new file mode 100755 index 0000000..d29d1fa --- /dev/null +++ b/10/10_2.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# 2021 - Advent Of Code - 10 part 2 + +def parse_file(file): + non_corrupted = [] + with open(file) as f: + i = 0 + for line in f.readlines(): + chunks = [] + corrupted = False + for c in line.strip(): + if c in close_sign.values(): # open signs + chunks.append(c) + elif c in close_sign: + last_open = chunks.pop() + if close_sign[c] != last_open: + # print(f'found corrupted chunk at line {i}: {line.strip()}') + count_score[c] += 1 + corrupted = True + break + if not corrupted: + non_corrupted.append(line.strip()) + i += 1 + print(f'nb lines: {i}') + + return non_corrupted + + +def complete_lines(lines): + completions = [] + for line in lines: + chunks = [] + for c in line: + if c in close_sign.values(): # open signs + chunks.append(c) + elif c in close_sign.keys(): + chunks.pop() + completion = [open_sign[c] for c in reversed(chunks)] + completions.append(completion) + return completions + + +close_sign = {')': '(', ']': '[', '}': '{', '>': '<'} +open_sign = {'(': ')', '[': ']', '{': '}', '<': '>'} +count_score = {')': 0, ']': 0, '}': 0, '>': 0} +score_table = {')': 1, ']': 2, '}': 3, '>': 4} + +# sequences = parse_file('input_example.txt') +sequences = parse_file('input.txt') +print(f'nb clean lines: {len(sequences)}') + +autocompletions = complete_lines(sequences) + +auto_score = [] +for a in autocompletions: + score = 0 + for sign in a: + score = score * 5 + score_table[sign] + auto_score.append(score) + +score = sorted(auto_score)[int(len(auto_score)/2)] +print(f'middle score: {score}')