Exemplo n.º 1
0
def stupid_algorithm(path = 'a_example.in'):
    rides, env_params = load_input(path)  
    for ride in rides:
        ride['Taken'] = False
    cars = {}
    for i in range(env_params['F']):
        cars[i] = {'pos': (0,0), 'time': 0, 'rides': []}
    T = env_params['T']
    B = env_params['B']
    score = 0
    cars_done = 0
    while cars_done < env_params['F']:
        for i, i_car in cars.items():
            chosen_ride, next_pos, next_time = choose_next_ride(i_car['pos'], i_car['time'], T, B, rides)
            if chosen_ride is None:
                cars_done += 1
                continue
            i_car['rides'].append(chosen_ride['ID'])
            score += take_ride(i_car, chosen_ride, T, B)
    print(score)
    save_path = path.split('.')[0]+'_schedule'
    with open(save_path, 'w') as f:
        for i, i_car in cars.items():
            i_rides = i_car['rides']
            outlist = [len(i_rides)]
            outlist.extend(i_rides)
            outlist = [str(x) for x in outlist]
            f.write(' '.join(outlist))
            f.write("\n")
Exemplo n.º 2
0
def evaluate(setup_path='a_example.in'):
    rides, env_params = load_input(setup_path)
    T = env_params['T']
    B = env_params['B']
    save_path = setup_path.split('.')[0]+'_schedule'
    for ride in rides:
        ride['Taken'] = False
    with open(save_path, 'r') as f:
        score = 0
        for row in f:
            row_lst = row.strip('\n').split(' ')
            car = {'pos': (0,0), 'time': 0, 'rides': []}
            for ride_ID_str in row_lst[1:len(row_lst)]:
                ride_ID = int(ride_ID_str)
                ride = get_ride(rides, ride_ID)
                if ride['Taken']:
                    raise ValueError()
                score += take_ride(car, ride, T, B)   
    return score
Exemplo n.º 3
0
"""
solution for day 11 part 1 and 2
"""
import re
import util

DAY11_INPUT = util.load_input('day11.input')[0]


def solve(input_data):
    """
    solve day 11 part 1 and 2
    """
    x_coor = 0
    y_coor = 0
    max_distance = 0
    for direction in re.split(r'[,]+', input_data):
        if direction == 'n':
            y_coor += 1
        elif direction == 'ne':
            x_coor += 1
            y_coor += 1
        elif direction == 'se':
            x_coor += 1
        if direction == 's':
            y_coor -= 1
        elif direction == 'sw':
            x_coor -= 1
            y_coor -= 1
        elif direction == 'nw':
            x_coor -= 1
Exemplo n.º 4
0
"""
solution for day 12 part 2
"""
import re
import util

DAY12_INPUT = util.load_input('day12.input')

def visit_programs(program, program_dict, visited_programs):
    """
    recursively visit connected programs remembering visited programs
    """
    connected_programs = program_dict[program]
    for connected_program in connected_programs:
        if not visited_programs[connected_program]:
            visited_programs[connected_program] = True
            visited_programs = zip_or(
                visited_programs,
                visit_programs(connected_program, program_dict, visited_programs))
    return visited_programs

def zip_or(visited_programs_1, visited_programs_2):
    """
    item wise or operation on two lists
    """
    return [x or y for x, y in zip(visited_programs_1, visited_programs_2)]

def solve(program, input_data):
    """
    solve day 12 part 2
    """
Exemplo n.º 5
0
    # If arrive at final mode then have found a path
    if not adjacency_dict[start]:
        return 1  # found a path
    else:
        # Only do dfs if we haven't already stored the number of paths from this start node to the final node
        if start not in cache.keys():
            # The number of paths to a node is the sum of number of paths to parent nodes
            cache[start] = sum(
                dfs_dp(adjacency_dict, c, cache)
                for c in adjacency_dict[start])
        return cache[start]


if __name__ == '__main__':
    filename = 'day_10.txt'
    data = load_input(filename, parse_line)

    data.sort()
    data.append(data[-1] + 3)
    data.insert(0, 0)

    diffs = []
    for x, y in zip(data, data[1:]):
        diffs.append(y - x)

    counts = {}
    for value in set(diffs):
        count = diffs.count(value)
        counts[value] = count

    print('Part 1')
Exemplo n.º 6
0
"""
solution for day 13
"""
import re
import util

DAY13_INPUT = util.load_input('day13.input')
TEST_INPUT = [\
    '0: 3',\
    '1: 2',\
    '4: 4',\
    '6: 4']


def solve(input_data):
    """
    solve day 13
    """
    layers = {}
    for line in input_data:
        data = re.split(r'[: ]', line)
        layers.update({int(data[0]):\
            {"scanner": 0, "direction": "down", "depth": int(data[2])}})

    position = 0
    score = 0

    while position <= max(layers.keys()):
        current_layer = layers.get(position)
        if current_layer is not None and current_layer["scanner"] == 0:
            score += position * current_layer["depth"]
Exemplo n.º 7
0
                program.weight = int(part[1:-1])
            elif index > 2:
                subprogram_name = part.rstrip(',')
                sub_program = programs.get(subprogram_name)
                if not sub_program:
                    sub_program = Program(subprogram_name)
                sub_program.parent = program
                programs[sub_program.name] = sub_program
                program.sub_programs.add(sub_program)
    any_program = programs.values()[0]
    while any_program.parent:
        any_program = any_program.parent
    return (any_program, programs)


ROOT, PROGRAMS = build_tree(util.load_input('day7.input'))

print "part 1: %s" % ROOT.name

ROOT.find_anomalies()
print PROGRAMS['anygv'].calculate_sub_programs_balances()

# anygv:3678 +
#     (tghfe:89 +
#         (usddqi:170 + (fgokr:19) + (mdznc:19) + (psynxr:19)) +
#         (zuphhfa:199 + (pkagrvq:14) + (ospcnv:14)) +
#         (rjzbhh:91 + (sarppfb:68) + (nhyhkq:68))) + # = 770
#     (fabacam:305 +
#         (dlcxjg:17 + (mhwqim:70) + (jcrmny:70)) +
#         (dlactl:127 + (lizkruo:15) + (jkhruz:15)) +
#         (falrf:97 + (sdezdnz:20) + (zttpfsd:20) + (zfaog:20))) + # = 776 -> 770 -> 305 -> **299**
Exemplo n.º 8
0
        print('Instruction not recognised')
    return address, accum


def play_program(program, address, accum, final_address):
    addresses_been = set()
    while address not in addresses_been and address != final_address:
        addresses_been.add(address)
        address, accum = perform_instruction(program[address], address, accum)

    return address, accum, address == final_address


if __name__ == '__main__':
    filename = 'day_8.txt'
    program = load_input(filename, parse_line)
    final_address = len(program)

    # Also test without change the first adress?
    for i in range(final_address + 1):
        p = deepcopy(program)
        if p[i][0] == 'nop':
            p[i][0] = 'jmp'
        elif p[i][0] == 'jmp':
            p[i][0] = 'nop'

        _, accum, done = play_program(p, 0, 0, final_address)
        if done:
            break
    print('Part 2 answer:', accum)
Exemplo n.º 9
0
"""
solution for day 9
"""
import util

DAY9_INPUT = util.load_input('day9.input')

OPEN_GROUP = '{'
CLOSE_GROUP = '}'
OPEN_COMMENT = '<'
CLOSE_COMMENT = '>'
IGNORE = '!'


def solve(input_data):
    """
    solve day 9 part 1 and 2
    """
    group_depth = 0
    comment_mode = False
    ignore_next = False
    score = 0
    garbage = 0

    for char in input_data[0]:
        if ignore_next:
            ignore_next = False
            continue
        elif comment_mode:
            if char == IGNORE:
                ignore_next = True
Exemplo n.º 10
0
    build the tree from given lines
    """
    programs = dict()
    for line in lines:
        program = Program()
        for index, part in enumerate(re.split(r'[ ]+', line)):
            if index == 0:
                if programs.get(part):
                    program = programs.get(part)
                program.name = part
                programs[part] = program
            elif index == 1:
                program.weight = int(part[1:-1])
            elif index > 2:
                subprogram_name = part.rstrip(',')
                sub_program = programs.get(subprogram_name)
                if not sub_program:
                    sub_program = Program(subprogram_name)
                sub_program.parent = program
                programs[sub_program.name] = sub_program
                program.programs.add(sub_program)
    any_program = programs.values()[0]
    root = any_program.name
    while any_program.parent:
        any_program = any_program.parent
        root = any_program.name
    return root


print build_tree(util.load_input('day7.input'))