def main(): intext = common.read_input(10) log.info('Initializing lists...') l_lengths = [int(n.strip()) for n in intext.split(',')] l_numbers = init_elements() log.info('Starting hash for part 1...') answer_1, _, _, _ = hash(l_lengths, l_numbers) print('The answer to part 1 is: {}'.format(answer_1)) # First, from now on, your input should be taken not as a list of numbers, but as a string of bytes instead l_lengths = get_ascii_sequence(common.read_input(10)) answer_2 = get_part_2_hash(l_lengths=l_lengths) print('The answer to part 2 is: {}'.format(answer_2))
def get_cleaned_input(): raw = read_input("data/day_03.txt") arr = str_to_array(raw) tree_ascii = 35 as_boolean = arr == tree_ascii return as_boolean
def main(): input = common.read_input(1) input_array = [int(c) for c in input] answer = sum_matches(input_array) answer2 = sum_matches_part2(input_array) print('The part 1 answer is: {}'.format(answer)) print('The part 2 answer is: {}'.format(answer2))
def generate_myoutput(): for i in range(CHALLENGES): cities = read_input(f'input_{i}.csv') solver, name = (mysolver, 'output') tour = solver.solve(cities) with open(f'{name}_{i}.csv', 'w') as f: f.write(format_tour(tour) + '\n')
def generate_sample_output(): for i in range(CHALLENGES): cities = read_input(f'input_{i}.csv') for solver, name in ((solver_random, 'random'), (solver_greedy, 'greedy')): tour = solver.solve(cities) with open(f'sample/{name}_{i}.csv', 'w') as f: f.write(format_tour(tour) + '\n')
def generate_sample_output(): for i in range(CHALLENGES): cities = read_input(f'input_{i}.csv') for solver, name in ((sample_solver_random, 'random'), (solver_greedy, 'greedy')): tour = solver.solve(cities) with open(f'sample/{name}_{i}.csv', 'w') as f: f.write(format_tour(tour) + '\n')
def generate_sample_output(solver, name): for i in range(CHALLENGES): cities = read_input(f'input_{i}.csv') tour = solver.solve(cities) # my_output/に作る with open(f'my_output/{name}_{i}.csv', 'w') as f: f.write(format_tour(tour) + '\n')
def main(): intext = common.read_input(13) layers = parse_input(s_input=intext) s = Scanner(layers=layers) s.run() log.info('Starting part 1...') answer_1 = s.score print('The answer to part 1 is: {}'.format(answer_1)) log.info('Starting part 2...') print('answer 2: {}'.format(part_2_stolen())) delay = 5500 while False and delay < 10**4: # log.info('Trying delay: {}'.format(delay)) layers = parse_input(s_input=intext) if delay % 2 == 1: delay += 1 continue # only even delays allow layer 1 to pass s = Scanner(layers=layers, delay=delay) s.run(short_circuit=True) if s.score == 0: break if delay % 500 == 0: log.info('Delay: {}'.format(delay)) log.debug('Delay: {}, Score: {}'.format(delay, s.score)) delay += 1 answer_2 = delay print('The answer to part 2 is: {}'.format(answer_2))
def check_vault_env_variable(): if os.environ.get("ANSIBLE_VAULT_PASSWORD") is None: pwd = common.read_input("Enter vault password", "", is_password=True) os.environ["ANSIBLE_VAULT_PASSWORD"] = pwd return pwd return ""
def main(): text = common.read_input(9) text, g_count = StrParser.cleanup_garbage(text) groups = StrParser.build_groups(text) answer_1 = StrParser.count_group_score(groups) print('The answer to part 1 is: {}'.format(answer_1)) answer_2 = g_count print('The answer to part 2 is: {}'.format(answer_2))
def main(): s_instr = common.read_input(8) rc = init_collection_from_input(s_instr) rc.proc(parse_input(s_instr)) answer_1 = max([r.value for r in rc.registers]) answer_2 = rc.max_seen print('The answer to part 1 is: {}'.format(answer_1)) print('The answer to part 2 is: {}'.format(answer_2))
def createInitial(k): k = 7 tour = read_input('input_' + str(k) + '.csv') n = len(tour) points = list(range(n)) inital = createConvexHull(tour) result = insertAtoB(set(points) - set(inital), inital) print(totalDistance(result), result)
def generate_sample_output(): for i in range(7,8): cities = read_input(f'input_{i}.csv') solver = solver_sa name = 'output' tour = solver.solve(cities) with open(f'{name}_{i}.csv', 'w') as f: f.write(format_tour(tour) + '\n')
def main(): jmps = parse_input(common.read_input(5)) js = JmpSet(jmps=jmps.copy()) t1 = timeit.timeit(js.proc) answer_1 = js.steps print('The answer to part 1 is: {} (took {} seconds)'.format(answer_1, t1)) js = JmpSet(jmps=jmps.copy()) t2 = timeit.timeit(js.proc2) answer_2 = js.steps print('The answer to part 2 is: {} (took {} seconds)'.format(answer_2, t2))
def generate_sample_solutions(): solvers = ((solver_random, 'random'), (solver_greedy, 'greedy'), (solver_yours,'yours')) for challenge_number in range(CHALLENGES): cities = read_input('input_{}.csv'.format(challenge_number)) for solver, solver_name in solvers: solution = solver.solve(cities) with open('solution_{}_{}.csv'.format(solver_name, challenge_number), 'w') as f: f.write(format_solution(solution) + '\n')
def generate_sample_solutions(): solvers = ((solver_random, 'random'), (solver_greedy, 'greedy')) for challenge_number in range(CHALLENGES): cities = read_input('input_{}.csv'.format(challenge_number)) for solver, solver_name in solvers: solution = solver.solve(cities) with open( 'solution_{}_{}.csv'.format(solver_name, challenge_number), 'w') as f: f.write(format_solution(solution) + '\n')
def split_group(data = read_input(sys.argv[1])): a_group = [] a_store = {} b_group = [] b_store = {} c_group = [] c_store = {} d_group = [] d_store = {} e_group = [] e_store = {} f_group = [] f_store = {} g_group = [] g_store = {} h_group = [] h_store = {} all_store = {} num = 0 for x, y in data: if 0 <= x < 400 : if 0 <= y <400 : a_group.append((x, y)) a_store[num] = (x, y) elif 400 <= y : e_group.append((x,y)) e_store[num] = (x, y) elif 400 <= x < 800 : if 0 <= y <400 : b_group.append((x, y)) b_store[num] = (x, y) elif 400 <= y : f_group.append((x,y)) f_store[num] = (x, y) elif 800 <= x < 1200 : if 0 <= y <400 : c_group.append((x, y)) c_store[num] = (x, y) elif 400 <= y : g_group.append((x,y)) g_store[num] = (x, y) elif 1200 <= x : if 0 <= y <400 : d_group.append((x, y)) d_store[num] = (x, y) elif 400 <= y : h_group.append((x,y)) h_store[num] = (x, y) num+=1 for idx, city in enumerate(data): all_store[idx] = city return a_group, b_group, c_group, d_group, e_group, f_group, g_group, h_group, \ a_store, b_store, c_store, d_store, e_store, f_store, g_store, h_store, all_store
def main(): intext = common.read_input(11) directions = parse_input(s_input=intext) t = Traveler() t.follow(directions) log.info('Starting part 1...') answer_1 = t.distance print('The answer to part 1 is: {}'.format(answer_1)) log.info('Starting part 2...') answer_2 = t.max_distance print('The answer to part 2 is: {}'.format(answer_2))
def main(): lines = parse_input(common.read_input(7)) towers = create_towers_from_input(lines) t_base = get_base_tower(towers) answer_1 = t_base.name print('The answer to part 1 is: {}'.format(answer_1)) unbalanced_tower = find_anomaly(towers) weight_corr = get_weight_correction(unbalanced_tower) new_weight = unbalanced_tower.weight + weight_corr if not verify_wrong_weight(unbalanced_tower, towers): log.error('The bad tower was not correct') sys.exit(1) answer_2 = new_weight print('The answer to part 2 is: {}'.format(answer_2))
def main(): passphrases = parse_input(common.read_input(4)) answer_1 = 0 answer_2 = 0 idx = 1 for p in passphrases: log.debug('Testing passphrase ({}/{})'.format(idx, len(passphrases))) idx += 1 if not has_duplicates(p): answer_1 += 1 if not has_anagrams(p): answer_2 += 1 print('The answer to part 1 is: {}'.format(answer_1)) print('The answer to part 2 is: {}'.format(answer_2))
def part_2_stolen(): """ Straigh ganked from https://www.reddit.com/r/adventofcode/comments/7jgyrt/2017_day_13_solutions/dr6bxce/ """ lines = [line.split(': ') for line in common.read_input(13).split('\n')] heights = {int(pos): int(height) for pos, height in lines} part1 = sum(pos * heights[pos] for pos in heights if scanner(heights[pos], pos) == 0) print('part1: {}'.format(part1)) part2 = next( wait for wait in itertools.count() if not any(scanner(heights[pos], wait + pos) == 0 for pos in heights)) return part2
def generate_sample_solutions(): # solvers = ((solver_random, 'random'), # (solver_greedy, 'greedy')) solvers = ((solver_divide_and_conquer, 'yours'), ) for challenge_number in range(CHALLENGES): cities = read_input('input/{}.csv'.format(challenge_number)) # other_solution = read_solution('solution_yours/divide_greedy2/{}.csv'.format(challenge_number)) for solver, solver_name in solvers: solution = solver.solve(cities) # solution = solver.solve(cities, other_solution) with open( 'solution_{}/{}.csv'.format(solver_name, challenge_number), 'w') as f: f.write(format_solution(solution) + '\n')
def generate_output(): for i in range(7, CHALLENGES): cities = read_input(f'input_{i}.csv') solver = solver_DSA name = 'dsa' #solver = solver_2_opt #name = '2_opt' record = [3292, 3779, 4495, 8150, 10676, 20273, 40000, 81000] tour, distance = solver.solve(cities) while distance > record[i]: tour, distance = solver.solve(cities) if distance <= record[i]: break with open(f'my_output/{name}_{i}_1.csv', 'w') as f: f.write(format_tour(tour) + '\n') '''
def verify_output(): for challenge_number in range(CHALLENGES): print(f'Challenge {challenge_number}') cities = read_input(f'./input/input_{challenge_number}.csv') N = len(cities) for output_prefix in ('output/greedy', 'output/best_greedy', 'output/two_opt', 'sample/sa','sample/change', 'output/one_or_opt', 'output/more_opt', 'sample/final'): output_file = f'{output_prefix}_{challenge_number}.csv' with open(output_file) as f: lines = f.readlines() assert lines[0].strip() == 'index' tour = [int(i.strip()) for i in lines[1:N + 1]] assert set(tour) == set(range(N)) path_length = sum(distance(cities[tour[i]], cities[tour[(i + 1) % N]]) for i in range(N)) print(f'{output_prefix:16}: {path_length:>10.2f}') print()
def verify_output(): for challenge_number in range(CHALLENGES): print(f'Challenge {challenge_number}') cities = read_input(f'input_{challenge_number}.csv') N = len(cities) for output_prefix in ('output', 'sample/random', 'sample/greedy', 'sample/sa'): output_file = f'{output_prefix}_{challenge_number}.csv' with open(output_file) as f: lines = f.readlines() assert lines[0].strip() == 'index' tour = [int(i.strip()) for i in lines[1:N + 1]] assert set(tour) == set(range(N)) path_length = sum(distance(cities[tour[i]], cities[tour[(i + 1) % N]]) for i in range(N)) print(f'{output_prefix:16}: {path_length:>10.2f}') print()
def verify_output(): for challenge_number in range(6, CHALLENGES): print(f'Challenge {challenge_number}') cities = read_input(f'input_{challenge_number}.csv') N = len(cities) for output_prefix in ('output', 'my_output/dsa'): output_file = f'{output_prefix}_{challenge_number}.csv' with open(output_file) as f: lines = f.readlines() assert lines[0].strip() == 'index' tour = [int(i.strip()) for i in lines[1:N + 1]] assert set(tour) == set(range(N)) path_length = sum( distance(cities[tour[i]], cities[tour[(i + 1) % N]]) for i in range(N)) print(f'{output_prefix:16}: {path_length:>10.2f}') print()
def verify_output(): for challenge_number in range(CHALLENGES): print(f'Challenge {challenge_number}') cities = read_input(f'input_{challenge_number}.csv') output_files = [] lengths = [] for output_prefix in PREFIXES: output_file = f'my_output/{output_prefix}_{challenge_number}.csv' path_length = get_path_length(output_file, cities) if path_length: output_files.append(output_file) lengths.append(path_length) print(f'{output_prefix:16}: {path_length:>10.2f}') best_output = output_files[lengths.index(min(lengths))] print(best_output) shutil.copyfile(f'{best_output}', f'output_{challenge_number}.csv') print()
def verify_solutions(): solutions = ('random', 'greedy', 'sa', 'yours') for challenge_number in range(CHALLENGES): print('Challenge {}'.format(challenge_number)) cities = read_input('input_{}.csv'.format(challenge_number)) N = len(cities) for solution_name in solutions: solution_file = 'solution_{}_{}.csv'.format(solution_name, challenge_number) with open(solution_file) as f: lines = f.readlines() assert lines[0].strip() == 'index' tour = [int(i.strip()) for i in lines[1:N + 1]] assert set(tour) == set(range(N)) path_length = sum(distance(cities[u], cities[v]) for u, v in zip(tour, tour[1:] + tour[0:1])) print('{:8}: {:>10.2f}'.format(solution_name, path_length)) print()
def verify_output(): for challenge_number in range(CHALLENGES): print(f'Challenge {challenge_number}') cities = read_input(f'./input/input_{challenge_number}.csv') N = len(cities) for output_prefix in ( 'output/random', 'output/bitDP', 'output/greedy', 'output/2opt', 'output/2opt_sa'): output_file = f'{output_prefix}_{challenge_number}.csv' try: with open(output_file) as f: lines = f.readlines() assert lines[0].strip() == 'index' tour = [int(i.strip()) for i in lines[1:N + 1]] assert set(tour) == set(range(N)) path_length = sum(distance(cities[tour[i]], cities[tour[(i + 1) % N]]) for i in range(N)) print(f'{output_prefix:16}: {path_length:>10.2f}') except BaseException: pass print()
#!/usr/bin/env python3 import math import sys sys.path.insert(0, './data') from common import print_solution, read_input, format_solution def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def solve(cities): # Build a trivial solution. # Visit the cities in the order they appear in the input. return list(range(len(cities))) if __name__ == '__main__': assert len(sys.argv) > 1 solution = solve(read_input("data/"+sys.argv[1])) #read first argument e.g. solver_random.py input_1.csv print_solution(solution) # print solution # print format_solution(solution)
#!/usr/local/bin/python3 import math import re from functools import partial, reduce from itertools import combinations from pprint import pprint from common import drop, last, read_input, take_while_list, window import numpy as np data = [int(l) for l in read_input('data.input.day9')] # do we care about processing? at least we'll use generators... # walk a window of preamble + 1, the last being the one we check def check(w): p = map(math.fsum, combinations(w[:-1], 2)) v = w[-1] return any(map(lambda n: n == v, p)) preamble = 25 ans = next(x for x in drop(preamble, window(preamble + 1, data)) if not check(x))[-1] # part 2 # find some set of at least 2 numbers that add to value from part 1 # i guess i still don't care about processing though...
while len(tabu_list) > size: tabu_list.pop(0) count = count + 1 #best_solution_ever.pop(-1) #print(best_cost) #print(best_solution_ever) print(self.total_dist(best_solution_ever)) return best_solution_ever # solve function def solve(cities): ts = TS(cities) tour = ts.tabu_search() return tour def solve_with_initial(cities, initial_tour): ts = TS(cities, initial_tour=initial_tour) tour = ts.tabu_search() return tour if __name__ == '__main__': assert len(sys.argv) > 1 cities = read_input(sys.argv[1]) tour = solve(cities) #print_tour(tour)
def main(): inlist = parse_input(common.read_input(2)) print('The answer to part 1 is: {}'.format(checksum(inlist))) print('The answer to part 2 is: {}'.format(checksum_part2(inlist)))
dist = [[0] * N for i in range(N)] for i in range(N): for j in range(N): dist[i][j] = dist[j][i] = distance(cities[i], cities[j]) current_city = 0 last_city_pos = 0 sum = 0 unvisited_cities = set(range(1, N)) solution = [current_city] def distance_from_current_city(to): return dist[current_city][to] while unvisited_cities: next_city = min(unvisited_cities, key=distance_from_current_city) sum += dist[current_city][next_city] unvisited_cities.remove(next_city) solution.append(next_city) current_city = next_city sum += dist[current_city][last_city_pos] print sum return solution if __name__ == '__main__': assert len(sys.argv) > 1 solution = solve(read_input("data/"+sys.argv[1])) print_solution(solution)
#!/usr/bin/env python 2 import math import sys from common import print_solution,read_input import random def distance(city1,city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def solve(cities): # Build a trivial solution. # Visit the cities in the order they appear in the input. return list(range(len(cities))) cities=read_input(sys.argv[1]) n=len(cities)-1 m=1 dis=0 while 1 : if m<=n: dis += distance(cities[m-1],cities[m]) m+=1 else: break total_dis=dis+distance(cities[0],cities[n]) print total_dis
probe = (base + 1) % N next_probe = (probe + 1) % N next_base = (base + 1) % N delta = 0 for j in range(N-3): if(count == 0): if(distance(cities[base], cities[next_base]) > distance(cities[next_base], cities[next_probe])): delta = distance(cities[base], cities[next_base]) - distance(cities[next_base], cities[next_probe]) cities = parcel_reverse(cities, next_base, probe) count += 1 else: if(distance(cities[base], cities[next_base]) + delta > distance(cities[next_base], cities[next_probe])): count += 1 delta = distance(cities[base], cities[next_base]) + distance(cities[probe], cities[next_probe]) - distance(cities[base], cities[probe]) - distance(cities[next_base], cities[next_base]) + delta cities = parcel_reverse(cities, next_base, probe) probe = (probe + 1) % N next_probe = (probe + 1) % N return cities if __name__ == '__main__': assert len(sys.argv) > 1 city = read_input(sys.argv[1]) solution = solve(city) solution = lin_kernighan(solution) solution = do_2opt(solution) solution = match_index(city, solution) write_solution(solution) #print_solution(solution)
elif path[i - 1] == x: path[i + 1] = y else: path[i + 1] = x return path # 探索 def kruskal_greedy(cities): size = len(cities) edges = make_edge(cities) edge_count = [0] * size u = unionfind(size) i = 0 select_edge = [] while i < size: e = edges.get() if (edge_count[e.p1] < 2 and edge_count[e.p2] < 2 and (u.find(e.p1) != u.find(e.p2) or i == size - 1)): u.unite(e.p1, e.p2) edge_count[e.p1] += 1 edge_count[e.p2] += 1 select_edge.append(e) i += 1 return edge_to_path(select_edge, size) if __name__ == '__main__': assert len(sys.argv) > 1 solution = kruskal_greedy(read_input(sys.argv[1])) print_solution(solution)
#!/usr/bin/env python3 import sys import math from itertools import * import solver_greedy from common import print_solution, read_input from intersect import doIntersect FILENAME = 'input_7.csv' INPUT = read_input(FILENAME) LENGTH = len(INPUT) solution = solver_greedy.solve(INPUT) class Tour(object): def __init__(self, solution): self.tour_list = solution self.tour_list.append(solution[0]) self.dist = [[0] * LENGTH for i in range(LENGTH)] for i in range(LENGTH): for j in range(LENGTH): self.dist[i][j] = self.dist[j][i] = solver_greedy.distance(INPUT[i], INPUT[j]) def getTour(self): return self.tour_list def intersectsWithSubsequentEdge(self, i): A, B = self.tour_list[i], self.tour_list[i+1] for j in range(i+1, LENGTH):
path[j1:j1] = [p] count += 1 total += count if count == 0: break return path, total def optimize2(cities, path): N = len(cities) dist = distance_table(cities) cnt = 0 while True: path, _ = opt_2(N, path, dist) path, flag = or_opt(N, path, dist) if flag == 0: cnt += 1 if cnt == 5: return path def read_path(filename): with open(filename) as f: path = [] for line in f.readlines()[1:]: # Ignore the first line. path.append(int(line)) return path if __name__ == '__main__': assert len(sys.argv) > 1 solution = optimize2(read_input(sys.argv[1]), read_path(sys.argv[2])) print_solution(solution)
table[(1 << size1) - 1] = [(distance_table[i][0], 0) for i in xrange(1, size)] for v in xrange((1 << size1) - 2, 0, -1): tmp = [1e300] * size1 for i in xrange(size1): if (1 << i) & v: tmp[i] = min0([(distance_table[i+1][j+1] + table[v | (1 << j)][j][0], j) \ for j in xrange(size1) if not (1 << j) & v]) table[v] = tmp s = min0([(distance_table[i+1][0] + table[1 << i][i][0], i) for i in xrange(size1)]) return s[0], get_min_path(table, size, s[1]) def get_min_path(table, size, p): path = [0, p + 1] v = 1 << p while len(path) < size: _, q = table[v][p] path.append(q + 1) v |= (1 << q) p = q return path point_table = read_input(sys.argv[1]) point_size = len(point_table) distance_table = distance(point_table) min_len, min_path = tsp_dp1(point_size) #min_len = tsp_dp(point_size) #min_path = [] print min_len print_solution(min_path)
from common import print_solution, read_input def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def greedy(cities): N = len(cities) dist = [[0] * N for i in range(N)] for i in range(N): for j in range(N): dist[i][j] = dist[j][i] = distance(cities[i], cities[j]) path = [i for i in range(N)] for i in range(N - 1): min_len = 1000000 min_pos = 0 for j in range(i + 1, N): l = dist[path[i]][path[j]] if l < min_len: min_len = l min_pos = j path[i + 1], path[min_pos] = path[min_pos], path[i + 1] return path if __name__ == '__main__': assert len(sys.argv) > 1 solution = greedy(read_input(sys.argv[1])) print_solution(solution)
kyori3 = dist[solution[a2]][solution[b-1]] kyori4 = dist[solution[a]][solution[b]] if (kyori1+kyori2) > (kyori3+kyori4): print "found!" solution[a:b] = solution[b-1:a-1:-1] print solution found = True break if found: print "break" break if not found: break; sum_kyori = 0 for i in range(N-1): sum_kyori += dist[solution[i]][solution[i+1]] sum_kyori += dist[solution[N-1]][solution[0]] print "ko-shin!" print sum_kyori return solution if __name__ == '__main__': assert len(sys.argv) > 1 solution = solve(read_input(sys.argv[1])) print_solution(solution)
import time start_time = time.time() # This code tries all permutaions - obviously not a good way (wanted to try it anywayws) # Only works for input_0.csv and input_1.csv def distance(city1, city2): city1, city2 = xy_list[city1], xy_list[city2] #city index to coordinate return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def try_everything(xy_list): shortest_dist= 100000000000000 start_city = 0 perms = itertools.permutations(range(1,len(xy_list)), len(xy_list)-1) for perm in perms: total_dist = distance(start_city, perm[0]) + distance(perm[len(perm)-1], start_city) i,j = 0, 1 while i < (len(perm)-1) and j < len(perm): total_dist += distance(perm[i], perm[j]) i+= 1 j+=1 if total_dist < shortest_dist: shortest_dist, best_route = total_dist, perm return best_route, shortest_dist if __name__ == '__main__': assert len(sys.argv) > 1 xy_list = read_input("data/"+sys.argv[1]) print try_everything(xy_list) print("RunTime: %s seconds" % (time.time() - start_time))
return tour def opt_2(tour, cities): for i in range(100000): point1 = int(random.uniform(1, len(tour))) point2 = int(random.uniform(1, len(tour))) while point2 == point1: point2 = int(random.uniform(1, len(tour))) orig = cal_dist(tour, cities) tour[point1], tour[point2] = tour[point2], tour[point1] updated = cal_dist(tour, cities) if orig < updated: tour[point1], tour[point2] = tour[point2], tour[point1] return tour def cal_dist(tour, cities): dist = 0 for i in range(len(tour)-1): # for i in range(tour-1): dist += distance(cities[tour[i]], cities[tour[i+1]]) dist += distance(cities[tour[len(tour)-1]], cities[0]) return dist if __name__ == '__main__': assert len(sys.argv) > 1 tmp_tour = greedy(read_input(sys.argv[1])) tour = opt_2(tmp_tour[:], read_input(sys.argv[1])) print_tour(tour) # print(cal_dist(tour, read_input(sys.argv[1])))
i0 = i - 1 i1 = i + 1 if i0 < 0: i0 = N - 1 if i1 == N: i1 = 0 for j in range(N): j1 = j + 1 if j1 == N: j1 = 0 if j != i and j1 != i: l1 = dist[path[i0]][path[i]] # i0 - i - i1 l2 = dist[path[i]][path[i1]] l3 = dist[path[j]][path[j1]] # j - j1 l4 = dist[path[i0]][path[i1]] # i0 - i1 l5 = dist[path[j]][path[i]] # j - i - j1 l6 = dist[path[i]][path[j1]] if l1 + l2 + l3 > l4 + l5 + l6: # つなぎかえる p = path[i] path[i:i + 1] = [] if i < j: path[j:j] = [p] else: path[j1:j1] = [p] count += 1 if count == 0: break return path if __name__ == '__main__': assert len(sys.argv) > 1 solution = or_opt(read_input(sys.argv[1])) print_solution(solution)
for i in range(N): for j in range(N): dist[i][j] = dist[j][i] = distance(cities[i], cities[j]) path = [i for i in range(N)] while True: count = 0 for i in range(N - 2): i1 = i + 1 for j in range(i + 2, N): if j == N - 1: j1 = 0 else: j1 = j + 1 if i != 0 or j1 != 0: l1 = dist[path[i]][path[i1]] l2 = dist[path[j]][path[j1]] l3 = dist[path[i]][path[j]] l4 = dist[path[i1]][path[j1]] if l1 + l2 > l3 + l4: # つなぎかえる new_path = path[i1:j+1] path[i1:j+1] = new_path[::-1] count += 1 if count == 0: break return path if __name__ == '__main__': assert len(sys.argv) > 1 solution = opt_2(read_input(sys.argv[1])) print_solution(solution)
from common import read_input, Const circuit = read_input() a_val = circuit.get('a').evaluate() for node_name in circuit.nodes.keys(): circuit.get(node_name).reset() circuit.get('b').value = Const(a_val) print circuit.get('a').evaluate()
def solve_by_list(lst, cities): dist_sum = 0.0 for i in range(-1,len(lst)-1): dist_sum += distance(cities[lst[i]], cities[lst[i+1]]) return dist_sum def solve_all(cities): # 体当たり seq = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) # seq = (0, 1, 2, 3, 4, 5, 6) list_all = list(itertools.permutations(seq)) result = 0.0 d = 0.0 for l in list_all: lst = list(l) lst.append(15) # lst.append(7) if result == 0.0: result = solve_by_list(lst, cities) else: d = solve_by_list(lst, cities) if result > d: result = d print result if __name__ == '__main__': assert len(sys.argv) > 1 # solution = solve(read_input(sys.argv[1])) # print_solution(solution) solve_all(read_input(sys.argv[1]))
from common import read_input, solve prefs = read_input() prefs['me'] # For the side-effect on defaultdict print solve(prefs)
from common import read_input, leader def race(reindeer, seconds): n = 0 while n < seconds: for r in reindeer: r.tick() n += 1 return reindeer def leader(reindeer): return max(reindeer, key=lambda r: r.position) print 'EXAMPLE' result = race(read_input('input.example'), 1000) print result print 'Won: %s' % leader(result) print 'REAL' result = race(read_input('input'), 2503) print result print 'Won: %s' % leader(result)
def fullsearch(cities): N = len(cities) global min_length, min_path min_length = 100000000 min_path = [] def fullsearch_sub(start, solution): global min_length, min_path dist = path_length(solution, cities) if dist > min_length: return if N == len(solution): new_len = path_length(solution, cities) if(new_len < min_length): min_length = new_len min_path = solution[:] else: for current_city in range(N): if current_city not in solution: solution.append(current_city) fullsearch_sub(current_city + 1, solution) solution.pop() for i in range(N): fullsearch_sub(i, min_path) return min_path if __name__ == '__main__': assert len(sys.argv) > 1 solution = fullsearch(read_input(sys.argv[1])) write_solution(solution) print_solution(solution)
from common import read_input, solve print solve(read_input())
l4 = dist[path[i0]][path[i1]] # i0 - i1 l5 = dist[path[j]][path[i]] # j - i - j1 l6 = dist[path[i]][path[j1]] if l1 + l2 + l3 > l4 + l5 + l6: # つなぎかえる p = path[i] path[i:i + 1] = [] if i < j: path[j:j] = [p] else: path[j1:j1] = [p] count += 1 total += count if count == 0: break return path, total def optimize(cities): N = len(cities) path = [i for i in range(N)] dist = distance_table(cities) while True: path, _ = opt_2(N, path, dist) path, flag = or_opt(N, path, dist) if flag == 0: return path if __name__ == '__main__': assert len(sys.argv) > 1 solution = optimize(read_input(sys.argv[1])) print_solution(solution)
def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def solve(cities): N = len(cities) dist = [[0] * N for i in range(N)] for i in range(N): for j in range(i, N): dist[i][j] = dist[j][i] = distance(cities[i], cities[j]) current_city = 0 unvisited_cities = set(range(1, N)) tour = [current_city] while unvisited_cities: next_city = min(unvisited_cities, key=lambda city: dist[current_city][city]) unvisited_cities.remove(next_city) tour.append(next_city) current_city = next_city return tour if __name__ == '__main__': assert len(sys.argv) > 1 tour = solve(read_input(sys.argv[1])) print_tour(tour)
def distance(i): return math.sqrt((cities[i][0] - cities[separate_before][0]) ** 2 + (cities[i][1] - cities[separate_before][1]) ** 2) while unvisited_cities: solution, separate_from, unvisited_cities = make_circle(cities, unvisited_cities) if (cnt % 2): solution.reverse() next = min(solution, key=distance) solution = solution[next:] + solution[:next] if (next > separate_from): separate_from += len(solution[:next]) else: separate_from -= next solution_f = solution[:separate_from] solution_e = solution[separate_from:] solution_e.reverse() solution_first.extend(solution_f) solution_end.extend(solution_e) cnt += 1 separate_before = separate_from solution_end.reverse() solution_first.extend(solution_end) return solution_first if __name__ == '__main__': assert len(sys.argv) > 1 solution = vortex(read_input(sys.argv[1])) print_solution(solution)
def solve(cities): N = len(cities) dist = [[0] * N for i in range(N)] for i in range(N): for j in range(i, N): dist[i][j] = dist[j][i] = distance(cities[i], cities[j]) # step = min(N, 10) step = 10**3 ans_tour = generate_greedy_tour(N, dist) ans_path_length = sum(distance(cities[ans_tour[i]], cities[ans_tour[(i + 1) % N]]) for i in range(N)) for i in range(step): # tmp_tour = generate_greedy_tour(N, dist, (200 * i) % N) tour, path_length = swap_cross(cities, dist, N) # tour, path_length = swap_cross(cities, dist, ans_tour, N) if path_length < ans_path_length: ans_tour = tour ans_path_length = path_length return ans_tour if __name__ == '__main__': assert len(sys.argv) > 1 tour = solve(read_input(sys.argv[1])) print_tour(tour)
import sys from common import read_input, print_solution from optimize import optimize from opt_2 import opt_2 from greedy import greedy from solver_greedy import solve from or_opt import or_opt from vortex import vortex from kruskal import kruskal_greedy from my_random import random_solve from combine import optimize2, read_path if __name__ == '__main__': assert len(sys.argv) > 1 optimize = optimize(read_input(sys.argv[1])) optimize2 = optimize2(read_input(sys.argv[1]), read_path(sys.argv[2])) greedy = greedy(read_input(sys.argv[1])) opt_2 = opt_2(read_input(sys.argv[1])) or_opt = or_opt(read_input(sys.argv[1])) vortex = vortex(read_input(sys.argv[1])) kruskal = kruskal_greedy(read_input(sys.argv[1])) print_solution(or_opt) print_solution(or_opt) print_solution(vortex) print_solution(kruskal) print_solution(greedy) print_solution(greedy) print_solution(optimize) print_solution(optimize)