![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
1 #######################Day1#################### 2 #################part1########################## 3 ''' 4 四舍五入法:直接使用int函数取整数即可 5 ''' 6 def get_math(str1): 7 # str1 = '100756' 8 res = int(int(str1)/3)-2 9 return res 10 li = [] 11 path = r'E:\厦门银行数据\santa\text.txt' 12 with open(path,'r',encoding='utf-8') as f: 13 text = f.readlines() 14 for i in text: 15 x = get_math(i.strip()) 16 li.append(x) 17 print(sum(li)) 18 #####################part2####################### 19 ''' 20 循环使用四舍五入法 21 加入判断,到小于0的时候停止 22 全部求和 23 ''' 24 str1 = '100756' 25 def get_math_2(str1): 26 li = [] 27 res = 1 28 while res>0: 29 res = int(int(str1)/3)-2 30 str1 = res 31 if res > 0: 32 li.append(res) 33 return sum(li) 34 li = [] 35 path = r'E:\厦门银行数据\santa\text.txt' 36 with open(path,'r',encoding='utf-8') as f: 37 text = f.readlines() 38 for i in text: 39 x = get_math_2(i.strip()) 40 li.append(x) 41 print(sum(li))
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
##################Day2####################### #################part1####################### # path = r'E:\厦门银行数据\santa\text.txt' # with open(path,'r',encoding='utf-8') as f: # text = f.readlines()[0] # import re # li = [int(i) for i in re.findall('\d+',text)] # def fun_plus(index,list): # li = list[index:index+4] # if li[0] == 1: # list[li[3]] = list[li[1]]+list[li[2]] # elif li[0] == 2: # list[li[3]] = list[li[1]] * list[li[2]] # elif li[0] == 99: # return list # else: # return list # for i in range(0,len(li),4): # li1 = fun_plus(i,li) # print(li) #################part2####################### # path = r'E:\厦门银行数据\santa\text.txt' # with open(path,'r',encoding='utf-8') as f: # text = f.readlines()[0] # import re # li = [int(i) for i in re.findall('\d+',text)] # # def fun_plus(index,list): # li = list[index:index+4] # if len(li)>2: # if li[1]*100+li[2] == 19690720: # print(li[1],li[2]) # # print(li[1]*100+li[2]) # if li[0] == 1: # list[li[3]] = list[li[1]]+list[li[2]] # elif li[0] == 2: # list[li[3]] = list[li[1]] * list[li[2]] # elif li[0] == 99: # return list # # # for a in range(100): # for b in range(100): # prg = [x for x in li] # prg[1] = a # prg[2] = b # for i in range(0, len(prg), 4): # fun_plus(i,prg) # if prg[0] == 19690720: # print(a * 100 + b) # exit()
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
import sys from collections import defaultdict test_0 = """R8,U5,L5,D3 U7,R6,D4,L4""" test_1 = """R75,D30,R83,U83,L12,D49,R71,U7,L72 U62,R66,U55,R34,D71,R55,D58,R83""" test_2 = """R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51 U98,R91,D20,R16,D67,R40,U7,R15,U6,R7""" DIRECTIONS = { 'R': (1, 0), 'L': (-1, 0), 'D': (0, -1), 'U': (0, 1) } def man_dist(x, y): return sum([abs(x[i] - y[i]) for i in range(0, 2)]) def walk_line(grid, line_1, line): pos = (0, 0) steps = 0 for ins in line_1: step = DIRECTIONS[ins[0]] for i in range(int(ins[1:])): steps += 1 pos = (pos[0] + step[0], pos[1] + step[1]) grid[pos].append((line, steps)) def print_grid(grid, x, y): for i in range(y): line = "" for j in range(x): wires = len([x[0] for x in grid[(j, i)]]) line += "*" if wires == 2 else "+" if wires == 1 else "." print(line) def part1(data): line_1 = data[0].split(',') line_2 = data[1].split(',') grid = defaultdict(list) walk_line(grid, line_1, 1) walk_line(grid, line_2, 2) min_dist = None for pos, lines in grid.items(): if len(set([l[0] for l in lines])) > 1: min_dist = min(min_dist, man_dist((0, 0), pos)) if min_dist else man_dist((0, 0), pos) return min_dist def part2(data): line_1 = data[0].split(',') line_2 = data[1].split(',') grid = defaultdict(list) walk_line(grid, line_1, 1) walk_line(grid, line_2, 2) combined_steps = None for pos, lines in grid.items(): if len(set([l[0] for l in lines])) > 1: this_combined_steps = sum([l[1] for l in lines]) combined_steps = min(this_combined_steps, combined_steps) if combined_steps else this_combined_steps return combined_steps if __name__ == '__main__': assert part1(test_0.split("\n")) == 6 assert part1(test_1.split("\n")) == 159 assert part1(test_2.split("\n")) == 135 assert part2(test_0.split("\n")) == 30 assert part2(test_1.split("\n")) == 610 assert part2(test_2.split("\n")) == 410 with open(r'E:\厦门银行数据\santa\text.txt','r') as f: data = f.readlines() print(part1(data)) print(part2(data))
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
##################Day4####################### #################part1####################### def day4_part1(): def find_number(number): for i in range(len(str(number))-1): if str(number)[i] ==str(number)[i+1]: return True else: return False def sort_number(number): number_list = list(str(number)) sort_value = sorted(number_list) if number_list == sort_value: return number else: return None res_list = [] for i in range(156218,652528,1): step_1 = find_number(i) if step_1: res = sort_number(i) if res: res_list.append(i) print(len(res_list)) #################part2####################### def day4_part2(): def find_number(number): for i in range(len(str(number))-1): if str(number)[i] ==str(number)[i+1] and len(re.findall(str(number)[i],str(number)))==2: return True else: return False def sort_number(number): number_list = list(str(number)) sort_value = sorted(number_list) if number_list == sort_value: return number else: return None res_list = [] for i in range(156218,652528,1): step_1 = find_number(i) if step_1: res = sort_number(i) if res: res_list.append(i) print(len(res_list))
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
def run(): def get_value(mode, program, address): if mode == 0: return program[program[address]] else: return program[address] def run_program(program, input): ip = 0 reg = input while ip < len(program): opcode = program[ip] % 100 modes = program[ip] // 100 if opcode == 1: program[program[ip + 3]] = get_value(modes % 10, program, ip + 1) \ + get_value(modes // 10, program, ip + 2) ip += 4 elif opcode == 2: program[program[ip + 3]] = get_value(modes % 10, program, ip + 1) \ * get_value(modes // 10, program, ip + 2) ip += 4 elif opcode == 3: program[program[ip + 1]] = reg ip += 2 elif opcode == 4: reg = get_value(modes % 10, program, ip + 1) ip += 2 elif opcode == 5: if get_value(modes % 10, program, ip + 1) != 0: ip = get_value(modes // 10, program, ip + 2) else: ip += 3 elif opcode == 6: if get_value(modes % 10, program, ip + 1) == 0: ip = get_value(modes // 10, program, ip + 2) else: ip += 3 elif opcode == 7: if get_value(modes % 10, program, ip + 1) < \ get_value(modes // 10, program, ip + 2): program[program[ip + 3]] = 1 else: program[program[ip + 3]] = 0 ip += 4 elif opcode == 8: if get_value(modes % 10, program, ip + 1) == \ get_value(modes // 10, program, ip + 2): program[program[ip + 3]] = 1 else: program[program[ip + 3]] = 0 ip += 4 elif opcode == 99: return reg with open(r"E:\厦门银行数据\santa\text.txt", "r") as f: program = list(map(lambda n: int(n), f.readline().split(","))) print(run_program(list(program), 1)) print(run_program(list(program), 5))
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
##################Day5####################### ##################part1####################### path = r'E:\厦门银行数据\santa\text.txt' li1 = [] li2 = [] with open(path, 'r', encoding='utf-8') as f: line = f.readlines() line = [i.strip() for i in line] for i in line: li1.append(i[0:3]) li2.append(i[4:7]) def find_str(s): if s == 'COM': return 'COM' else: return li1[li2.index(s)] def for_loop(s): lis = [] while True: lis.append(s) s = find_str(s) if s == 'COM': lis.append(s) break return len(lis)-1 def run_day_5(): number = [] for i in li2: number.append(for_loop(i)) print(sum(number)) ##################part2####################### def find_str_2(s): if s == 'COM': return 'COM' else: return li1[li2.index(s)] def for_loop_2(s): lis = [] while True: lis.append(s) s = find_str_2(s) if s == 'COM': lis.append(s) break return lis def run_day_5_2(): number = [] for i in li2: number.append(for_loop_2(i)) return number def result_day_5(): n = run_day_5_2() you = [] san = [] for i in n: if 'YOU' in i: you.append(i) elif 'SAN' in i: san.append(i) # for i in you[0]: # if i in san[0]: # print(i) ###第一个相交的位置就是最近的位置为W1N res = 'W1N' you = you[0][0:you[0].index('W1N')] san = san[0][0:san[0].index('W1N')] you.remove('YOU') san.remove('SAN') you.append('W1N') for i in san: you.append(i) print(len(you)-1)
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
https://github.com/moozzyk/AdventOfCode2019/tree/master/Day07 from itertools import permutations class Amplifier: def __init__(self, program, input, output): self.program = program self.input = input self.output = output self.ip = 0 def get_value(self, mode, offset): address = self.ip + offset if mode == 0: return self.program[self.program[address]] else: return self.program[address] def run(self): while self.ip < len(self.program): opcode = self.program[self.ip] % 100 modes = self.program[self.ip] // 100 m1 = modes % 10 m2 = modes // 10 if opcode == 1: self.program[self.program[self.ip + 3]] = ( self.get_value(m1, 1) + self.get_value(m2, 2)) self.ip += 4 elif opcode == 2: self.program[self.program[self.ip + 3]] = ( self.get_value(m1, 1) * self.get_value(m2, 2)) self.ip += 4 elif opcode == 3: if len(self.input) == 0: return False self.program[self.program[self.ip + 1]] = self.input.pop(0) self.ip += 2 elif opcode == 4: self.output.append(self.get_value(m1, 1)) self.ip += 2 elif opcode == 5: if self.get_value(m1, 1) != 0: self.ip = self.get_value(m2, 2) else: self.ip += 3 elif opcode == 6: if self.get_value(m1, 1) == 0: self.ip = self.get_value(m2, 2) else: self.ip += 3 elif opcode == 7: if self.get_value(m1, 1) < self.get_value(m2, 2): self.program[self.program[self.ip + 3]] = 1 else: self.program[self.program[self.ip + 3]] = 0 self.ip += 4 elif opcode == 8: if self.get_value(m1, 1) == self.get_value(m2, 2): self.program[self.program[self.ip + 3]] = 1 else: self.program[self.program[self.ip + 3]] = 0 self.ip += 4 elif opcode == 99: return True def create_amplifiers(program, phases): pipes = [] for s in phases: pipes.append([s]) amplifiers = [] for i in range(0, len(pipes)): in_pipe = pipes[i] out_pipe = pipes[(i + 1) % len(pipes)] amplifiers.append(Amplifier(list(program), in_pipe, out_pipe)) return amplifiers def calculate_thrust(amplifiers): current = 0 amplifiers[0].input.append(0) while not amplifiers[current].run() or current != len(amplifiers) - 1: current = (current + 1) % len(amplifiers) return amplifiers[0].input[0] def solve(program, phases): max_thrust = 0 for subset in permutations(phases): amplifiers = create_amplifiers(program, subset) thrust = calculate_thrust(amplifiers) max_thrust = max(thrust, max_thrust) print(max_thrust) with open(r'E:\厦门银行数据\santa\text.txt', "r") as f: program = list(map(lambda n: int(n), f.readline().split(","))) solve(program, [0, 1, 2, 3, 4]) solve(program, [5, 6, 7, 8, 9])
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
##################Day7####################### ##################part1####################### def day_7_part_1(): path = r'E:\厦门银行数据\santa\text.txt' with open(path,'r') as f: text = f.readlines()[0] li = [] for i in range(0,len(text),25): li.append(list(text)[i:i+25]) number_li = [] for i in range(0,len(li),6): number_0 = 0 number_1 = 0 number_2 = 0 for i in li[i:i+6]: number_0 += i.count('0') number_1 += i.count('1') number_2 += i.count('2') number_li.append([number_0,number_1,number_2]) for i in number_li: if i[0] == min([i[0] for i in number_li]): print(i[1]*i[2]) ##################part2####################### def run_day_7_part_2(): path = r'E:\厦门银行数据\santa\text.txt' with open(path,'r') as f: text = f.readlines()[0] li = [] for i in range(0,len(text),25): li.append(list(text)[i:i+25]) number_li = [] for i in range(0,len(li),6): x = li[i:i+6][0]+li[i:i+6][1]+li[i:i+6][2]+li[i:i+6][3]+li[i:i+6][4]+li[i:i+6][5] number_li.append(x) length_x = len(number_li[0]) length_y = len(number_li) total_li = [] for x in range(length_x): x_li = [] for y in range(length_y): x_li.append(number_li[y][x]) total_li.append(x_li) def find_number(li): for i in li: if i == '2': pass else: return i res = [] for i in total_li: res.append(find_number(i)) # print(''.join(res)) text = ''.join(res) li = [] for i in range(0,len(text),25): li.append(list(text)[i:i+25]) # print(li) for i in li: print(' '.join(i).replace('0',' '))
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
class Intcode: def __init__(self, program, input, output): self.memory = {i: program[i] for i in range(len(program))} self.input = input self.output = output self.ip = 0 self.base = 0 def get_value_at(self, address): return self.memory.get(address, 0) def get_value(self, mode, offset): address = self.ip + offset if mode == 0: return self.get_value_at(self.get_value_at(address)) if mode == 2: return self.get_value_at(self.base + self.get_value_at(address)) return self.get_value_at(address) def set_value(self, mode, offset, value): address = self.get_value_at(self.ip + offset) if mode == 2: address = self.base + address self.memory[address] = value def run(self): while True: opcode = self.get_value_at(self.ip) % 100 modes = self.get_value_at(self.ip) // 100 m1 = modes % 10 modes = modes // 10 m2 = modes % 10 modes = modes // 10 m3 = modes % 10 if opcode == 1: value = self.get_value(m1, 1) + self.get_value(m2, 2) self.set_value(m3, 3, value) self.ip += 4 elif opcode == 2: value = self.get_value(m1, 1) * self.get_value(m2, 2) self.set_value(m3, 3, value) self.ip += 4 elif opcode == 3: if len(self.input) == 0: return False self.set_value(m1, 1, self.input.pop(0)) self.ip += 2 elif opcode == 4: self.output.append(self.get_value(m1, 1)) self.ip += 2 elif opcode == 5: if self.get_value(m1, 1) != 0: self.ip = self.get_value(m2, 2) else: self.ip += 3 elif opcode == 6: if self.get_value(m1, 1) == 0: self.ip = self.get_value(m2, 2) else: self.ip += 3 elif opcode == 7: if self.get_value(m1, 1) < self.get_value(m2, 2): self.set_value(m3, 3, 1) else: self.set_value(m3, 3, 0) self.ip += 4 elif opcode == 8: if self.get_value(m1, 1) == self.get_value(m2, 2): self.set_value(m3, 3, 1) else: self.set_value(m3, 3, 0) self.ip += 4 elif opcode == 9: self.base += self.get_value(m1, 1) self.ip += 2 elif opcode == 99: return True def solve(program, input_val): output = [] intcode = Intcode(program, [input_val], output) intcode.run() print(output) with open(r'E:\厦门银行数据\santa\text.txt', "r") as f: program = list(map(lambda n: int(n), f.readline().split(","))) solve(program, 1) solve(program, 2)
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
##################Day10####################### ##################part1####################### def day10_part1(): import math grid = open(r"E:\厦门银行数据\santa\text.txt", "r").read().strip().split() asteroids = [(r, c) for (r, line) in enumerate(grid) for (c, e) in enumerate(line) if e == '#'] print(max(map(len, map( lambda cand: set(map( lambda a: math.atan2((a[1]-cand[1]), (a[0]-cand[0])), [a for a in asteroids if a != cand] )), asteroids )))) ##################part2####################### def day10_part2(): import math grid = open(r"E:\厦门银行数据\santa\text.txt", "r").read().strip().split() asteroids = [(r, c) for (r, line) in enumerate(grid) for (c, e) in enumerate(line) if e == '#'] def angle_dist(a): return (math.atan2(a[1], -a[0]), a[0]**2+a[1]**2) vlen = list(map(len, map( lambda cand: set(map( lambda a: math.atan2((a[1]-cand[1]), (a[0]-cand[0])), [a for a in asteroids if a != cand] )), asteroids ))) cannon = asteroids[vlen.index(max(vlen))] hook = (-0.5, 0) targets = [(a[0]-cannon[0], a[1]-cannon[1]) for a in asteroids if a != cannon] targets.append(hook) targets = sorted(targets, key=angle_dist) idx = targets.index(hook) targets = targets[idx+1:]+targets[:idx] last = None idx = 0 shots = [] while len(targets) > 0: shots.append(targets[idx]) last = targets[idx] del targets[idx] if len(targets) == 0: break idx %= len(targets) next_idx = idx while angle_dist(last)[0] == angle_dist(targets[next_idx])[0]: next_idx = (next_idx+1)%len(targets) if next_idx == idx: break idx = next_idx coord = list(map(lambda a: (a[0]+cannon[0], a[1]+cannon[1]), shots))[199] print(coord[1]*100+coord[0])
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
import time now = time.time() puzzle_input = 59704438946400225486037825889922820489843190285276623851650874501661128988396696069718826434708024511422795921838800269789913960190601300910423350290846455187315936154437526204822336114717910853157866334743979157700934791877134865819338701289349073169567308015162696370931073040617799608862983736292169088603858502137085782889297989277130087242942506416164598910622349994697403064628500493847458293153920207889114082230150603182206031692080645433361960358161328125435922180533297727179785114625861941781083443388701883640778753411135944703959349861504604264349715262460922987816868400261327556306957183739232107401756998929158348201149705670138765039 base_pattern = [0,1,0,-1] cycles = 100 ins = [int(x) for x in str(puzzle_input)] patterns = [] for i in range(len(ins)): pattern = [] for p in base_pattern: pattern.extend([p]*(i+1)) new_pattern = pattern.copy() while len(new_pattern) < len(ins)+1: new_pattern += pattern patterns.append(new_pattern[1:]) print ('Patterns ', time.time()-now) for cycle in range(cycles): result = [] for i in range(len(ins)): result.append(abs(sum([(n*p) for n, p in zip(ins, patterns[i])]))%10) # print(cycle, 'Input: ', ins, 'Output: ', result) ins = result.copy() print ('100 Cycles: ', time.time()-now) eight = ''.join([str(n) for n in ins[:8]]) print(f'First 8 digits: {eight}') # Patterns 0.04687309265136719 # 100 Cycles: 7.156249284744263 # First 8 digits: 19944447 import time now = time.time() puzzle_input = 59704438946400225486037825889922820489843190285276623851650874501661128988396696069718826434708024511422795921838800269789913960190601300910423350290846455187315936154437526204822336114717910853157866334743979157700934791877134865819338701289349073169567308015162696370931073040617799608862983736292169088603858502137085782889297989277130087242942506416164598910622349994697403064628500493847458293153920207889114082230150603182206031692080645433361960358161328125435922180533297727179785114625861941781083443388701883640778753411135944703959349861504604264349715262460922987816868400261327556306957183739232107401756998929158348201149705670138765039 base_pattern = [0,1,0,-1] cycles = 100 offset = int(str(puzzle_input)[:7]) ins = [int(x) for x in str(puzzle_input)] ins = ins*10_000 ins = ins[offset:] for cycle in range(100): for i in range(len(ins)-2, -1, -1): ins[i] = ins[i] + ins[i+1] ins[i] = ins[i] % 10 print ('Part 02: ', time.time()-now) eight = ''.join([str(n) for n in ins[:8]]) print(f'First 8 digits: {eight}')
![](http://img.e-com-net.com/image/info8/2b246dbcfe82488397e9aa432bbc4e31.gif)
def calculate_energy(values): result = [] for v in values: r = 0 for i in v: r += abs(i) result.append(r) return result def update_velocity(moons, velocities): coordinate = 0 while coordinate < 3: for idx1 in range(len(moons)): for idx2 in range(len(moons)): if moons[idx1][coordinate] > moons[idx2][coordinate]: velocities[idx1][coordinate] -= 1 elif moons[idx1][coordinate] < moons[idx2][coordinate]: velocities[idx1][coordinate] += 1 coordinate += 1 for m in range(len(moons)): for c in range(3): moons[m][c] += velocities[m][c] def problem1(moons): velocities = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] for _ in range(10000000000): update_velocity(moons, velocities) # print(moons) print('进行到%s'%_) if moons == [[-3, 10, -1], [-12, -10, -5], [-9, 0, 10], [7, -5, -3]]: print(_) break # pot = calculate_energy(moons) # kin = calculate_energy(velocities) # total = 0 # for i in range(len(pot)): # total += pot[i] * kin[i] # print(total) moons = [[-3, 10, -1], [-12, -10, -5], [-9, 0, 10], [7, -5, -3]] problem1(list(moons))