コード例 #1
0
    tokens = file_in.split('\n')
    num_minutes = int(tokens[0])

    arr = np.array([int(x) for x in tokens[1:1 + num_minutes]], dtype=np.int)

    return arr


def solve_level1(arr):
    return str(np.argmin(arr))


if __name__ == '__main__':

    in_path = 'input/level1/'
    out_path = 'output/level1/'

    files = os.listdir(in_path)
    files = [f for f in files if f.endswith('.in')]

    # files = ['level1_example.in']

    for f in files:
        file = read_file(os.path.join(in_path, f))
        df = create_df(file)
        solution = solve_level1(df)
        print(solution)

        write_solution(os.path.join(out_path, f.replace('.in', '.out')),
                       solution)
コード例 #2
0
ファイル: solve.py プロジェクト: jrmysvr/aoc_python
    return amps[-1].get_output()


if __name__ == "__main__":
    day = 7
    year = 2019
    input_text = get_input_text(day, year)

    ## Part 1 ##
    phase_settings = [0, 1, 2, 3, 4]
    int_code = text_to_intcode(input_text)
    highest_thrust = 0
    best_settings = []
    for settings in permutations(phase_settings):
        print("==========================")
        thrust = run_trial(int_code, settings)
        highest_thrust = max(thrust, highest_thrust)
        if thrust == highest_thrust:
            best_settings = settings

    print("\n==========================")
    print(f"Solution Day {day} (Part 1):")
    print(f"The highest thrust was {highest_thrust}")
    print(f"given by the phase settings {best_settings}")
    write_solution(day, year, str(highest_thrust))

    ## Part 2 ##
    #  print(f"Solution Day {day} (Part 2):")

    #  write_solution(day, year,
コード例 #3
0
    return 100 * noun + verb


if __name__ == "__main__":
    day = 2
    year = 2019
    input_text = get_input_text(day, year)

    int_code = map(int, input_text.split(","))

    initial_state = list(int_code)
    initial_state[1] = 12
    initial_state[2] = 2

    end_state = run(initial_state)

    ## Part 1 ##
    print(f"Solution Day {day} (Part 1):")
    print("\tEnd State - First Position: ", end_state[0])

    write_solution(day, year, str(end_state[0]))

    ## Part 2 ##
    print(f"Solution Day {day} (Part 2):")

    expected = 19690720
    noun, verb = brute_force(initial_state, expected)
    noun_verb = format_output(noun, verb)
    print(f"\tThe Noun/Verb which provided {expected} are: {noun_verb}")
    write_solution(day, year, str(noun_verb), part_2=True)
コード例 #4
0
# Autoencoder parameters
sae_decay = 1e-5
scl_decay = 1e-5
n_hid = [200]
rho = 0.1
beta = 3
method = 'L-BFGS-B'
n_iter = 5000

# cv_err = []
# for idx,(tr_idx,val_idx) in enumerate(dp.cross_val_idx(m_tr)):
# 	stacked_net = dac.DeepAutoencoderClassifier(d=d,k=k,n_hid=n_hid,sae_decay=sae_decay,scl_decay=scl_decay,rho=rho,beta=beta) # create a new classifier for each iteration of CV
# 	stacked_net.fit(X_tr[:,tr_idx],y_tr[:,tr_idx],method=method,n_iter=n_iter)
# 	pred,mce = stacked_net.predict(X_tr[:,val_idx],y_tr[:,val_idx])
# 	cv_err.append(mce)
# 	print 'Iteration',idx+1,'error:',100*mce,'%'
# avg_err = 1.*sum(cv_err)/len(cv_err)
# print 'Average Cross-validation Error:',100.*(avg_err),'%'

stacked_net = dac.DeepAutoencoderClassifier(d=d,
                                            k=k,
                                            n_hid=n_hid,
                                            sae_decay=sae_decay,
                                            scl_decay=scl_decay,
                                            rho=rho,
                                            beta=beta)
stacked_net.fit(X_tr, y_tr, method=method, n_iter=n_iter)
pred = stacked_net.predict(X_te)
utils.write_solution(path, 'deep_autoencoder', m_te, pred)
コード例 #5
0
ファイル: solve.py プロジェクト: jrmysvr/aoc_python
    year = 2019
    input_text = get_input_text(day, year)
    orbits = input_text.strip("\n").split("\n")
    planet_pairs = [orbit.split(")") for orbit in orbits]
    all_planets = dict()
    for (planet_name, in_orbit_name) in planet_pairs:
        planet = Planet(planet_name)
        if planet.name in all_planets:
            planet = all_planets.get(planet.name)
        orbit_planet = Planet(in_orbit_name)
        if orbit_planet.name in all_planets:
            orbit_planet = all_planets.get(orbit_planet.name)
        orbit_planet.set_orbit_of(planet)
        all_planets[planet.name] = planet
        all_planets[orbit_planet.name] = orbit_planet

    for name in all_planets:
        planet = all_planets[name]
    orbit_sum = sum([planet.count_indirect_orbits()
                     for planet in all_planets.values()])
    ## Part 1 ##
    print(f"Solution Day {day} (Part 1):")
    print("The number of direct and indirect orbits is", orbit_sum)

    write_solution(day, year, str(orbit_sum))

    ## Part 2 ##
    #  print(f"Solution Day {day} (Part 2):")

    #  write_solution(day, year,
コード例 #6
0
def solve(infile: str, outfile: str, level=ERROR):
    global log
    global lock_explode_v2
    log = Logger(os.path.split(infile)[1], level=level)
    start_time = time.time()

    robots, obstacles, name = utils.read_scene(infile)
    invalid_positions = load_occupied_positions(robots, obstacles)
    grid = create_grid(robots, invalid_positions)
    graph = create_graph(grid, invalid_positions)
    remained_distance = update_robots_distances(robots, graph)
    start_distance = remained_distance
    log.info(f'Started! {remained_distance} distance')
    robots = sort_robots(robots)
    robots_dsts = list(map(lambda robot: robot.target_pos, robots))
    steps = []  # a data structure to hold all the moves for each robot
    step_number = 0
    total_moves = 0
    while is_not_finished(robots) and is_not_stuck(
            steps):  # while not all robots finished
        steps.append(
            dict())  # each step holds dictionary <robot_index,next_direction>
        stuck_robots = []

        for robot in robots:
            condition = (
                abs_distance(robot.target_pos, robot.current_pos) == 3 and
                (utils.calc_next_pos(robot.target_pos, RIGHT)
                 in invalid_positions and utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, RIGHT),
                     RIGHT) in invalid_positions
                 or utils.calc_next_pos(robot.target_pos, RIGHT) in obstacles
                 or utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, RIGHT),
                     RIGHT) in obstacles) and
                (utils.calc_next_pos(robot.target_pos, LEFT)
                 in invalid_positions and utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, LEFT),
                     LEFT) in invalid_positions
                 or utils.calc_next_pos(robot.target_pos, LEFT) in obstacles
                 or utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, LEFT),
                     LEFT) in obstacles) and
                (utils.calc_next_pos(robot.target_pos, DOWN)
                 in invalid_positions and utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, DOWN),
                     DOWN) in invalid_positions
                 or utils.calc_next_pos(robot.target_pos, DOWN) in obstacles
                 or utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, DOWN),
                     DOWN) in obstacles) and
                (utils.calc_next_pos(robot.target_pos, UP) in invalid_positions
                 and utils.calc_next_pos(
                     utils.calc_next_pos(robot.target_pos, UP),
                     UP) in invalid_positions
                 or utils.calc_next_pos(robot.target_pos, UP) in obstacles or
                 utils.calc_next_pos(utils.calc_next_pos(robot.target_pos, UP),
                                     UP) in obstacles))
            if condition:
                log.critical(f'CONDITION {robot.index}')

            blocked_count = sum([
                utils.calc_next_pos(robot.target_pos, RIGHT)
                in invalid_positions and invalid_positions[utils.calc_next_pos(
                    robot.target_pos,
                    RIGHT)].occupied_type == PERMANENT_OCCUPIED,
                utils.calc_next_pos(robot.target_pos, LEFT)
                in invalid_positions and invalid_positions[utils.calc_next_pos(
                    robot.target_pos,
                    LEFT)].occupied_type == PERMANENT_OCCUPIED,
                utils.calc_next_pos(robot.target_pos, UP) in invalid_positions
                and invalid_positions[utils.calc_next_pos(
                    robot.target_pos, UP)].occupied_type == PERMANENT_OCCUPIED,
                utils.calc_next_pos(robot.target_pos, DOWN)
                in invalid_positions and invalid_positions[utils.calc_next_pos(
                    robot.target_pos,
                    DOWN)].occupied_type == PERMANENT_OCCUPIED
            ])
            if blocked_count == 4 and (abs_distance(
                    robot.current_pos, robot.target_pos) == 2 or condition):
                log.critical(f'EXPLODE id={robot.index}')
                robot.stuck_count = 777
            elif (abs_distance(robot.current_pos, robot.target_pos) == 2 or condition) and \
                    blocked_count == 3 and lock_explode_v2 is None \
                    and not calc_sp(step_number, robot, invalid_positions)[1]:
                log.critical(f'EXPLODE V2 id={robot.index}')
                robot.stuck_count = 777
                lock_explode_v2 = robot.index

        stuck_hard_robots = [
            robot for robot in robots if robot.stuck_count > 10
        ][:1]
        right_robots, up_robots, down_robots, left_robots = [], [], [], []
        for robot in stuck_hard_robots:
            log.critical(
                f'STUCK HARD ROBOT {robot.index}, count={robot.stuck_count}!!!'
            )
            robot_pos = robot.current_pos if robot.stuck_count != 777 else robot.target_pos

            right_robots = []
            start_pos = robot_pos
            next_right = [
                robot for robot in robots
                if robot.current_pos == utils.calc_next_pos(start_pos, RIGHT)
            ]
            while len(next_right) > 0:
                right_robots.extend(next_right)
                start_pos = next_right[0].current_pos
                next_right = [
                    robot for robot in robots
                    if robot.current_pos == utils.calc_next_pos(
                        start_pos, RIGHT)
                ]
            left_robots = []
            start_pos = robot_pos
            next_left = [
                robot for robot in robots
                if robot.current_pos == utils.calc_next_pos(start_pos, LEFT)
            ]
            while len(next_left) > 0:
                left_robots.extend(next_left)
                start_pos = next_left[0].current_pos
                next_left = [
                    robot for robot in robots
                    if robot.current_pos == utils.calc_next_pos(
                        start_pos, LEFT)
                ]
            up_robots = []
            start_pos = robot_pos
            next_up = [
                robot for robot in robots
                if robot.current_pos == utils.calc_next_pos(start_pos, UP)
            ]
            while len(next_up) > 0:
                up_robots.extend(next_up)
                start_pos = next_up[0].current_pos
                next_up = [
                    robot for robot in robots
                    if robot.current_pos == utils.calc_next_pos(start_pos, UP)
                ]
            down_robots = []
            start_pos = robot_pos
            next_down = [
                robot for robot in robots
                if robot.current_pos == utils.calc_next_pos(start_pos, DOWN)
            ]
            while len(next_down) > 0:
                down_robots.extend(next_down)
                start_pos = next_down[0].current_pos
                next_down = [
                    robot for robot in robots
                    if robot.current_pos == utils.calc_next_pos(
                        start_pos, DOWN)
                ]
            right_robots = [r for r in right_robots if r != robot]
            up_robots = [r for r in up_robots if r != robot]
            down_robots = [r for r in down_robots if r != robot]
            left_robots = [r for r in left_robots if r != robot]
            total_moves = explode_position(robot_pos, right_robots[::-1],
                                           left_robots[::-1], up_robots[::-1],
                                           down_robots[::-1],
                                           invalid_positions, steps,
                                           step_number, total_moves,
                                           stuck_robots, robots_dsts, robots)
            robot.prev_pos = None
            robot.way_blocked = []
            robot.self_block = []
            if robot.current_pos != robot.target_pos:
                total_moves, _ = turn(robot, invalid_positions, steps,
                                      step_number, total_moves, stuck_robots,
                                      True, robots_dsts)
        turn_robots = [
            robot for robot in robots
            if robot not in (stuck_hard_robots + right_robots + up_robots +
                             down_robots + left_robots)
        ]
        for robot in turn_robots:  # move each robot accordingly to its priority
            if robot.current_pos != robot.target_pos:
                total_moves, _ = turn(robot, invalid_positions, steps,
                                      step_number, total_moves, stuck_robots,
                                      False, robots_dsts)
        for robot in stuck_robots:  # move each robot accordingly to its priority
            if robot.current_pos != robot.target_pos:
                total_moves, _ = turn(robot, invalid_positions, steps,
                                      step_number, total_moves, stuck_robots,
                                      True, robots_dsts)
        sides_robots = [
            r for r in right_robots + up_robots + down_robots + left_robots
        ]
        robots = sides_robots + [r for r in stuck_hard_robots] + \
                 [r for r in robots if r not in stuck_robots and r not in stuck_hard_robots and r not in sides_robots] + \
                 [r for r in stuck_robots if r not in stuck_hard_robots and r not in sides_robots]
        clean_invalid_position(invalid_positions)
        step_number += 1

    # after the algorithm finished, we should write the moves data structure to json file.
    utils.write_solution(steps, name, outfile)

    remained_distance = update_robots_distances(robots, graph)
    total_time = time.time() - start_time
    if not is_not_finished(robots):
        log.info(
            f'Finished! {total_time}s, {step_number} steps, {total_moves} moves, {remained_distance} distance'
        )
        root_log.warn('Success!')
        return {
            'succeed': True,
            'total_time': total_time,
            'number_of_steps': step_number,
            'number_of_moves': total_moves,
            'remained_distance': remained_distance,
            'start_distance': start_distance
        }
    else:
        log.info(
            f'Stuck! {total_time}s, {step_number} steps, {total_moves} moves, {remained_distance} distance'
        )
        return {
            'succeed': False,
            'total_time': total_time,
            'number_of_steps': step_number,
            'number_of_moves': total_moves,
            'remained_distance': remained_distance,
            'start_distance': start_distance
        }
コード例 #7
0
ファイル: solve.py プロジェクト: jrmysvr/aoc_python
        common (Coordinate): coordinate to compare with the other coordinates

    Return:
        int of the smallest distance between a Coordinate and the common coordinate
    """
    distances = [
        common.distance_between(coordinate) for coordinate in coordinates
    ]
    return min(distances)


if __name__ == "__main__":
    day = 3
    year = 2019
    input_text = get_input_text(day, year)

    ## Part 1 ##
    wire_1, wire_2 = parse_wires(input_text)
    intersecting_coordinates = find_intersections(wire_1, wire_2)
    closest_distance = distance_to_closest_coordinate(intersecting_coordinates,
                                                      Coordinate(0, 0))
    print(f"Solution Day {day} (Part 1):")
    print("\tThe distance to the closest intersection is", closest_distance)

    write_solution(day, year, str(closest_distance))

    ## Part 2 ##
    #  print(f"Solution Day {day} (Part 2):")

    #  write_solution(day, year,
コード例 #8
0
ファイル: solve.py プロジェクト: jrmysvr/aoc_python
    Returns:
        int of fuel requirement for the given mass
    """

    fuel = (mass // 3) - 2
    return fuel + calculate_fuel_recur(fuel) if fuel > 0 else 0


if __name__ == "__main__":
    day = 1
    year = 2019
    input_text = get_input_text(day, year)

    ## Part 1 ##
    # Get Mass Values
    masses = parse_masses(input_text)

    # Calculate the Total Fuel Requirement
    total_fuel = sum(list(map(calculate_fuel, masses)))
    print("Solution Day 1 (Part 1):")
    print("\tTotal Fuel Requirement:", total_fuel)

    write_solution(day, year, str(total_fuel))

    ## Part 2 ##
    total_fuel = sum(list(map(calculate_fuel_recur, masses)))
    print("Solution Day 1 (Part 2):")
    print("\tTotal Fuel Requirement:", total_fuel)

    write_solution(day, year, str(total_fuel), part_2=True)
コード例 #9
0
    return all([is_valid(password) for is_valid in predicates])


def count_valid_passwords(low: int, high: int) -> int:
    """ Count valid passwords between `low` and `high` values (both inclusive)"""
    def is_valid(password) -> bool:
        return is_valid_password(password, low, high)

    return len(list(filter(bool, map(is_valid, range(low, high + 1)))))


if __name__ == "__main__":
    day = 4
    year = 2019
    input_text = get_input_text(day, year)

    low, high = parse_range(input_text)
    count = count_valid_passwords(low, high)
    # Part 1 solution had different criteria that was invalidated with Part 2
    #  print(f"Solution Day {day} (Part 1):")
    #  print("\tThe number of valid passwords between"
    #  f" {low} and {high} is {count}")

    # write_solution(day, year, str(count))

    print(f"Solution Day {day} (Part 2):")
    print("\tThe number of valid passwords between"
          f" {low} and {high} is {count}")

    write_solution(day, year, str(count), part_2=True)
コード例 #10
0
ファイル: svm_tests.py プロジェクト: avasbr/kaggle_related
y_tr = dp.read_csv_file(train_label_path)
m_tr,d = X_tr.shape
m_te = X_te.shape[0]

X_tr,(mu,s) = dp.normalize_range(X_tr,axis=0)
# C_range = 10.0**np.arange(-2,9)
# gamma_range = 10.0**np.arange(-5,4)
# cv = StratifiedKFold(y=y_tr,n_folds=5)
# param_grid = dict(gamma=gamma_range,C=C_range)
# grid = GridSearchCV(svm.SVC(),param_grid=param_grid,cv=cv)
# grid.fit(X_tr,y_tr)

# print(grid.best_estimator_)

cv_err = []
for idx,(tr_idx,val_idx) in enumerate(dp.cross_val_idx(m_tr)):
	clf = svm.SVC(C=1e6,gamma=0.001)
	clf.fit(X_tr[tr_idx,:],y_tr[tr_idx])
	pred = clf.predict(X_tr[val_idx,:])
	mce = 1.0-np.mean(pred==y_tr[val_idx])
	cv_err.append(mce)
	print 'Iteration',idx+1,'error:',100*mce,'%'
avg_err = 1.*sum(cv_err)/len(cv_err)
print 'Average Cross-validation Error:',100.*(avg_err),'%'

clf = svm.SVC(C=1e6,gamma=0.001)
X_te = (X_te - mu)/s
pred = clf.fit(X_tr,y_tr).predict(X_te)
utils.write_solution(path,'svm',m_te,pred)
コード例 #11
0
def main():
    start = time.time()  # Start time.
    os.system('cls' if os.name == 'nt' else 'clear')  # Clears the terminal.

    # Handles the arguments.
    if len(sys.argv) == 3:
        # If the args are 3 no output file name wasn't specified.
        method = sys.argv[1]
        input_file = sys.argv[2]
    elif len(sys.argv) == 4:
        # If the args are 4 the output file name was specified.
        method = sys.argv[1]
        input_file = sys.argv[2]
        output_file = sys.argv[3]
    else:
        print(
            f'Usage: {sys.argv[0]} <search algorithm> <problem file name> <solution file name>')
        print('- search algorithms: depth (Depth First), breadth (Breadth First), best (Best First), astar (A*)')
        sys.exit()

    # Initializes the type of queue based on the search method.
    search_queue = utils.METHODS[method]

    # Parse the data and get the objects (blocks), initial state and the goal state.
    data = utils.load_problem(input_file)
    objects = utils.get_objects_from_file(data)
    initial_state = utils.get_initial_state(data)
    goal_state = utils.get_goal_state(data)

    print('OBJECTS:', objects)

    print('\n#################### INITIAL STATE ####################\n')
    print(initial_state)
    i_blocks = utils.initialize_blocks(objects, initial_state)

    print('\n#################### GOAL STATE ####################\n')
    print(goal_state)
    g_blocks = utils.initialize_blocks(objects, goal_state)

    solution_node = search(search_queue, method, i_blocks, g_blocks)

    if solution_node != None:
        # If a solution is found.
        print('\n#################### SOLUTION ####################\n')
        solution_node.print_state()
        print(f'Number of moves: {solution_node.g}')

        # Calculates the time it took to find the solution.
        print('Took: ', time.time() - start)

        solution_path = solution_node.get_moves_to_solution()

        if len(sys.argv) == 3:
            # If the output file name was not specified.
            try:
                # Handling the paths with forward-slashes and back-slashes.
                file_name = input_file.split('\\')[-1]
                output_file = './solutions/' + method + '-' + file_name
                utils.write_solution(output_file, solution_path)
            except FileNotFoundError:
                file_name = input_file.split('/')[-1]
                output_file = './solutions/' + method + '-' + file_name
                utils.write_solution(output_file, solution_path)
        else:
            # If the output file name is specified.
            utils.write_solution(output_file, solution_path)
    else:
        print('Took: ', time.time() - start)
        print('############ ONE MINUTE PASSED AND NO SOLUTION WAS FOUND ############')
        sys.exit()
コード例 #12
0
# 	pred,mce = scl_net.predict(X_t[:,val_idx],y[:,val_idx])
# 	cv_err.append(mce)
# avg_err = 1.*sum(cv_err)/len(cv_err)
# print 'Cross-validation error:',100.*(avg_err),'%'

print 'Training a network with layer-wise pre-training'

# Autoencoder parameters
sae_decay = 1e-5
scl_decay = 1e-5
n_hid = [200]
rho = 0.1
beta = 3
method = 'L-BFGS-B'
n_iter = 5000

# cv_err = []
# for idx,(tr_idx,val_idx) in enumerate(dp.cross_val_idx(m_tr)):
# 	stacked_net = dac.DeepAutoencoderClassifier(d=d,k=k,n_hid=n_hid,sae_decay=sae_decay,scl_decay=scl_decay,rho=rho,beta=beta) # create a new classifier for each iteration of CV
# 	stacked_net.fit(X_tr[:,tr_idx],y_tr[:,tr_idx],method=method,n_iter=n_iter)
# 	pred,mce = stacked_net.predict(X_tr[:,val_idx],y_tr[:,val_idx])
# 	cv_err.append(mce)
# 	print 'Iteration',idx+1,'error:',100*mce,'%'
# avg_err = 1.*sum(cv_err)/len(cv_err)
# print 'Average Cross-validation Error:',100.*(avg_err),'%'

stacked_net = dac.DeepAutoencoderClassifier(d=d,k=k,n_hid=n_hid,sae_decay=sae_decay,scl_decay=scl_decay,rho=rho,beta=beta)
stacked_net.fit(X_tr,y_tr,method=method,n_iter=n_iter)
pred = stacked_net.predict(X_te)
utils.write_solution(path,'deep_autoencoder',m_te,pred)
コード例 #13
0
y_tr = dp.read_csv_file(train_label_path)
m_tr, d = X_tr.shape
m_te = X_te.shape[0]

X_tr, (mu, s) = dp.normalize_range(X_tr, axis=0)
# C_range = 10.0**np.arange(-2,9)
# gamma_range = 10.0**np.arange(-5,4)
# cv = StratifiedKFold(y=y_tr,n_folds=5)
# param_grid = dict(gamma=gamma_range,C=C_range)
# grid = GridSearchCV(svm.SVC(),param_grid=param_grid,cv=cv)
# grid.fit(X_tr,y_tr)

# print(grid.best_estimator_)

cv_err = []
for idx, (tr_idx, val_idx) in enumerate(dp.cross_val_idx(m_tr)):
    clf = svm.SVC(C=1e6, gamma=0.001)
    clf.fit(X_tr[tr_idx, :], y_tr[tr_idx])
    pred = clf.predict(X_tr[val_idx, :])
    mce = 1.0 - np.mean(pred == y_tr[val_idx])
    cv_err.append(mce)
    print 'Iteration', idx + 1, 'error:', 100 * mce, '%'
avg_err = 1. * sum(cv_err) / len(cv_err)
print 'Average Cross-validation Error:', 100. * (avg_err), '%'

clf = svm.SVC(C=1e6, gamma=0.001)
X_te = (X_te - mu) / s
pred = clf.fit(X_tr, y_tr).predict(X_te)
utils.write_solution(path, 'svm', m_te, pred)