Exemplo n.º 1
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines(as_type=int)
        # Do common input processing here

    def is_valid_number_at(self, idx):
        if idx < 25:
            return True
        val = self.lines[idx]
        is_valid = False
        for i in range(25):
            is_valid |= (val - self.lines[idx - i]) in self.lines[idx - 25:idx]
        return is_valid

    def get_part1_result(self):
        for i in range(len(self.lines)):
            if not self.is_valid_number_at(i):
                return self.lines[i]

    def get_part2_result(self):
        magic_number = self.get_part1_result()
        for i in range(len(self.lines)):
            total = 0
            j = i
            numbers = []
            while total < magic_number:
                total += self.lines[j]
                numbers.append(self.lines[j])
                j += 1
            if total == magic_number:
                return min(numbers) + max(numbers)
Exemplo n.º 2
0
class MyClass:
  def __init__(self, input_file):
    self.input = InputManager(input_file)
    line_groups = self.input.get_lines(group=True)
    rule_lines = line_groups[0]
    self.rules = Rules(rule_lines)
    self.my_ticket = Ticket(line_groups[1][1])
    self.nearby_tickets = [Ticket(l) for l in line_groups[2][1:]]
    self.valid_tickets = []

  def get_part1_result(self):
    invalid_fields_sum = 0
    for ticket in self.nearby_tickets:
      invalid_fields = self.rules.get_invalid_fields(ticket)
      if len(invalid_fields) == 0:
        self.valid_tickets.append(ticket)
      else:
        invalid_fields_sum += sum(invalid_fields)
    return invalid_fields_sum

  def get_part2_result(self):
    self.valid_tickets.append(self.my_ticket)
    self.rules.test_rules(self.valid_tickets)
    departure_product = 1
    for idx in range(len(self.rules.solved_rules)):
      if self.rules.solved_rules[idx].name.startswith('departure'):
        departure_product *= self.my_ticket[idx]
    return departure_product
Exemplo n.º 3
0
class PasswordManager:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.passwords = [
            list(line.split(':')) for line in self.input.get_lines()
        ]
        self.valid_passwords = [
            x[1] for x in self.passwords if self.is_pw_valid(*x)
        ]
        self.valid_passwords_part2 = [
            x for x in self.passwords if self.is_pw_valid_part2(*x)
        ]
        self.invalid_passwords_part2 = [
            x for x in self.passwords if not self.is_pw_valid_part2(*x)
        ]

    def is_pw_valid(self, rule, pw):
        range_str, char = rule.split()
        lower, upper = range_str.split('-')
        if int(lower) <= pw.count(char) <= int(upper):
            return True

    def is_pw_valid_part2(self, rule, pw):
        pw = pw.strip()
        range_str, char = rule.split()
        lower, upper = range_str.split('-')
        return (pw[int(lower) - 1] == char) ^ (pw[int(upper) - 1] == char)

    def get_final_result(self):
        return len(self.valid_passwords_part2)
Exemplo n.º 4
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.jolts = [0] + self.input.get_lines(as_type=int)
        self.jolts.append(max(self.jolts) + 3)
        self.jolts.sort()
        self.cnt = 0
        self.permutation_counts = {}
        # Do common input processing here

    def get_part1_result(self):
        jolts_array = np.array(self.jolts)
        diff = list(jolts_array[1:] - jolts_array[0:-1])
        print(max(diff))
        return diff.count(1) * diff.count(3)

    def count_permutations(self, idx):
        if idx in self.permutation_counts:
            return self.permutation_counts[idx]
        cnt = 0
        if idx == len(self.jolts) - 1:
            cnt = 1
        else:
            i = idx + 1
            while i < len(
                    self.jolts) and (self.jolts[i] - self.jolts[idx]) < 4:
                cnt += self.count_permutations(i)
                i += 1
        self.permutation_counts[idx] = cnt
        return cnt

    def get_part2_result(self):
        return self.count_permutations(0)
        pass
Exemplo n.º 5
0
class MyClass:
  def __init__(self, input_file):
    self.input = InputManager(input_file)
    self.lines = self.input.get_lines()
    # Do common input processing here

  def get_part1_result(self):
    pass

  def get_part2_result(self):
    pass
Exemplo n.º 6
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        self.code_runner = CodeRunner(self.lines)

    def get_part1_result(self):
        return self.code_runner.run_code()[1]

    def get_part2_result(self):
        return self.code_runner.run_modified_code()
Exemplo n.º 7
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)

    def find_2020_part2(self):
        numbers = np.array(self.input.get_lines(as_type=int)).reshape(-1, 1, 1)
        numbers_vert = numbers.reshape(1, -1, 1)
        numbers_3 = numbers.reshape(1, 1, -1)
        sums = numbers + numbers_vert + numbers_3
        print(sums)
        for i, mat in enumerate(sums):
            for j, row in enumerate(mat):
                for k, val in enumerate(row):
                    if val == 2020:
                        return (numbers[i], numbers[j], numbers[k])

    def find_2020(self):
        numbers = np.array(self.input.get_lines(as_type=int))
        numbers_vert = numbers.reshape(-1, 1)
        sums = numbers + numbers_vert
        for i, row in enumerate(sums):
            for j, val in enumerate(row):
                if val == 2020:
                    return (numbers[i], numbers[j])

    def find_2020_product_fast(self):
        numbers = np.array(self.input.get_lines(as_type=int))
        for i in numbers:
            for j in numbers:
                for k in numbers:
                    if (i + j + k) == 2020:
                        return i * j * k

    def get_final_result(self):
        # num1, num2, num3 = self.find_2020_part2()
        # print(num1, num2, num3)
        # return num1*num2*num3
        return self.find_2020_product_fast()
Exemplo n.º 8
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        self.program = BitMaskProgram(self.lines)

    def get_part1_result(self):
        self.program.execute_code()
        return self.program.get_memory_sum()

    def get_part2_result(self):
        self.program.reset()
        self.program.execute_code_part2()
        return self.program.get_memory_sum()
Exemplo n.º 9
0
class MyClass:
  def __init__(self, input_file):
    self.input = InputManager(input_file)
    self.lines = self.input.get_lines()
    self.seating_area = SeatingArea(self.lines)
    # print(self.seating_area)

  def get_part1_result(self):
    while not self.seating_area.is_stable():
      self.seating_area.iterate_area()
      # print(self.seating_area)
    return np.count_nonzero(self.seating_area.seats == SeatType.OCCUPIED)
    

  def get_part2_result(self):
    pass
Exemplo n.º 10
0
class MyClass:
  def __init__(self, input_file):
    self.input = InputManager(input_file)
    self.lines = self.input.get_lines()
    # Do common input processing here


  def get_part1_result(self):
    result_sum = 0
    for line in self.lines:
      res = eval_all_expressions(line)
      result_sum += res
    return result_sum

  def get_part2_result(self):
    pass
Exemplo n.º 11
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        self.earliest_time = int(self.lines[0])
        self.bus_schedules = []
        for bus_id in self.lines[1].split(','):
            if bus_id.strip() == 'x':
                self.bus_schedules.append(None)
            else:
                self.bus_schedules.append(BusSchedule(int(bus_id.strip())))

    def get_part1_result(self):
        min_delta_t = np.inf
        min_id = None
        for bus in self.bus_schedules:
            if bus is None:
                continue
            delta_t = bus.get_delta_t_after(self.earliest_time)
            if delta_t < min_delta_t:
                min_delta_t = delta_t
                min_id = bus.interval
        return min_delta_t * min_id

    def get_part2_result(self):
        soln_found = False
        k = 0
        last_known_match_idx = 0
        increment = 1
        while not soln_found:
            k += increment
            soln_found = True
            for i, bus in enumerate(self.bus_schedules):
                if bus is None or i <= last_known_match_idx:
                    continue
                delta_t = bus.get_delta_t_after(
                    k * self.bus_schedules[0].interval, i)
                soln_found &= (i == delta_t)
                if soln_found:
                    last_known_match_idx = i
                    increment *= bus.interval
                else:
                    break
        return k * self.bus_schedules[0].interval
Exemplo n.º 12
0
class MyClass:
  def __init__(self, input_file):
    self.input = InputManager(input_file)
    self.lines = self.input.get_lines()
    # Do common input processing here
    self.ship_location = ShipLocation()

  def get_part1_result(self):
    for command in self.lines:
      self.ship_location.move(command)
    return self.ship_location.get_manhattan_distance()

  def get_part2_result(self):
    # Reset ship location
    self.ship_location = ShipLocation()
    for command in self.lines:
      self.ship_location.move_to_wp(command)
    return self.ship_location.get_manhattan_distance()
Exemplo n.º 13
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        self.boarding_passes = []
        self.get_boarding_passes()

    def get_boarding_passes(self):
        for l in self.lines:
            row_str = self.convert_to_binary(l[0:7])
            col_str = self.convert_to_binary(l[7:10])
            row = int(row_str, 2)
            col = int(col_str, 2)
            seat_id = row * 8 + col
            self.boarding_passes.append({
                'row': row,
                'col': col,
                'id': seat_id
            })

    def convert_to_binary(self, s):
        return s.replace('F', '0').replace('B',
                                           '1').replace('L',
                                                        '0').replace('R', '1')

    def get_part1_result(self):
        max_id = 0
        for bp in self.boarding_passes:
            max_id = max(bp['id'], max_id)
        return max_id

    def get_part2_result(self):
        valid_ids = set(range(0, 128 * 8))
        for bp in self.boarding_passes:
            valid_ids.remove(bp['id'])
        for x in valid_ids:
            if not ((x + 1) in valid_ids or (x - 1) in valid_ids):
                return x
Exemplo n.º 14
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines(strip_whitespace=False)
        # Do common input processing here
        self.groups = []
        self.get_groups()
        # print(self.groups)

    def get_groups(self):
        self.current_group = []
        for l in self.lines:
            if l == '\n':
                self.groups.append(self.current_group)
                self.current_group = []
            else:
                self.current_group.append(l.strip())
        self.groups.append(self.current_group)

    def get_part1_result(self):
        total_count = 0
        for group in self.groups:
            unique_answers = set()
            for line in group:
                for char in line:
                    unique_answers.add(char)
            total_count += len(unique_answers)
        return total_count

    def get_part2_result(self):
        total_count = 0
        for group in self.groups:
            group_answers = [set(c for c in line) for line in group]
            common_answers = group_answers[0]
            for answers in group_answers:
                common_answers.intersection_update(answers)
            total_count += len(common_answers)
        return total_count
Exemplo n.º 15
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        initial_plane = []
        for line in self.lines:
            line_vals = []
            for ch in line:
                if ch == GridCell.EMPTY:
                    line_vals.append(0)
                elif ch == GridCell.OCCUPIED:
                    line_vals.append(1)
                else:
                    raise RuntimeError("Bad input")
            initial_plane.append(line_vals)
        self.cube_grid = CubeGrid(np.array(initial_plane))

    def get_part1_result(self):
        self.cube_grid.simulate(6)
        return self.cube_grid.count_occupied()

    def get_part2_result(self):
        pass
Exemplo n.º 16
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines()
        # Do common input processing here
        self.rules = self.get_rules()
        # print(self.rules)
        self.flattened_rules = self.flatten_rules()
        print(self.flattened_rules)
        self.contains_colors_dict = self.get_contains_colors_dict(
            self.flattened_rules)

    def get_rules(self):
        # rule = {color: [(cnt0, contains_color0), (cnt1, contains_color1), ...], ...}
        # Example: light red bags contain 1 bright white bag, 2 muted yellow bags.
        #   -> {'light red': [(1, 'bright white'), (2, 'muted yellow')], ...}
        rules = {}
        for l in self.lines:
            words = l.split()
            color = ' '.join(words[0:2])
            contains_strs = l.split('contain')[1].strip().strip('.').split(',')
            contains_list = []
            for c_str in contains_strs:
                if c_str == "no other bags":
                    break
                words = c_str.split()
                cnt = int(words[0])
                contains_color = ' '.join(words[1:3])
                contains_list.append((cnt, contains_color))
            rules[color] = contains_list
        return rules

    def flatten_rules(self):
        return {
            color: self.get_bags_list(color)
            for color in self.rules.keys()
        }

    def get_bags_list(self, color, multiplier=1):
        bags_list = []
        contains_list = self.rules[color]
        if len(contains_list) == 0:
            return bags_list
        for cnt, contains_color in contains_list:
            bags_list.append((multiplier * cnt, contains_color))
            bags_list.extend(
                self.get_bags_list(contains_color, multiplier * cnt))
        return bags_list

    def get_contains_colors_dict(self, rules):
        contains_colors_dict = defaultdict(set)
        for color, contains_colors in rules.items():
            for cnt, contains_color in contains_colors:
                contains_colors_dict[color].add(contains_color)
        return contains_colors_dict

    def get_part1_result(self):
        shiny_gold_cnt = 0
        for color, contains_colors in self.contains_colors_dict.items():
            if 'shiny gold' in contains_colors:
                shiny_gold_cnt += 1
        return shiny_gold_cnt

    def get_part2_result(self):
        total_contained_bags = 0
        for cnt, contains_color in self.flattened_rules['shiny gold']:
            total_contained_bags += cnt
        return total_contained_bags
Exemplo n.º 17
0
class MyClass:
    def __init__(self, input_file):
        self.input = InputManager(input_file)
        self.lines = self.input.get_lines(strip_whitespace=False)
        # Do common input processing here
        self.get_passports()
        self.required_keys = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
        self.complete_passports = []
        self.get_complete_passports()
        self.valid_passports = []
        self.get_valid_passports()
        # self.required_keys = ['byr','iyr','eyr','hgt','hcl','ecl','pid','cid',]

    def get_passports(self):
        self.passports = []
        current_pp = {}
        for l in self.lines:
            # print("line = '", l, "'")
            if l == '\n':
                self.passports.append(current_pp.copy())
                current_pp = {}
            else:
                for pair in l.split():
                    k, v = pair.split(':')
                    current_pp[k.strip()] = v.strip()
        if len(current_pp) > 0:
            self.passports.append(current_pp)
        # print(self.passports)

    def get_complete_passports(self):
        complete_pp_cnt = 0
        for p in self.passports:
            is_valid = True
            for k in self.required_keys:
                if k not in p.keys():
                    is_valid = False
                    break
            if is_valid:
                complete_pp_cnt += 1
                self.complete_passports.append(p)

    def get_valid_passports(self):
        for p in self.complete_passports:
            is_valid = True
            for k, v in p.items():
                if not self.is_valid(k, v):
                    is_valid = False
                    break
            if is_valid:
                self.valid_passports.append(p)

    def is_valid(self, key, value):
        is_pair_valid = True
        if key == 'byr':
            is_pair_valid = len(value) == 4 and (1920 <= int(value) <= 2002)
        elif key == 'iyr':
            is_pair_valid = len(value) == 4 and (2010 <= int(value) <= 2020)
        elif key == 'eyr':
            is_pair_valid = len(value) == 4 and (2020 <= int(value) <= 2030)
        elif key == 'hgt':
            if len(value) < 4:
                is_pair_valid = False
            else:
                ending = value[-2:]
                num = int(value[:-2])
                is_pair_valid = (ending == 'in' and
                                 (59 <= num <= 76)) or (ending == 'cm' and
                                                        (150 <= num <= 193))
        elif key == 'hcl':
            re_str = '#[0-9a-f]{6}'
            is_pair_valid = re.search(re_str,
                                      value) is not None and len(value) == 7
        elif key == 'ecl':
            is_pair_valid = value in [
                'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'
            ]
        elif key == 'pid':
            re_str = '[0-9]{9}'
            is_pair_valid = re.search(re_str,
                                      value) is not None and len(value) == 9
        elif key == 'cid':
            is_pair_valid = True
        return is_pair_valid

    def get_part1_result(self):
        return len(self.complete_passports)

    def get_part2_result(self):
        return len(self.valid_passports)