From f6ff66ea2da1f30303f17a2dac341411fb325881 Mon Sep 17 00:00:00 2001 From: blenovo Date: Sat, 16 Aug 2025 00:38:26 +0200 Subject: final puzzle and little cleanup for 2018 --- 2018/aoc2018-d05.py | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 2018/aoc2018-d05.py (limited to '2018/aoc2018-d05.py') diff --git a/2018/aoc2018-d05.py b/2018/aoc2018-d05.py new file mode 100644 index 0000000..6ebd839 --- /dev/null +++ b/2018/aoc2018-d05.py @@ -0,0 +1,64 @@ +#advent of code 2018 +#day 05 +#part 1 and 2 + +#extremely slow, rewrite candidate + +def polymer_d(a,b): + return (cdiff == abs(ord(a) - ord(b))); + +def polymer_strip(inp): + is_poly = True; + while is_poly: + is_poly = False; + for x in range(1,len(inp)): + x1 = inp[x-1]; + x2 = inp[x]; + if polymer_d(x1,x2): + #print((x1+x2)); + inp = inp.replace((x1+x2),""); + #myinput = myinput[ + is_poly = True; + break; + return inp; + +#part1 +def PolymerReaction(myinput): + is_poly = True; + while is_poly: + is_poly = False; + sub = ""; + for x in range(2,len(myinput)): + x1 = myinput[x-2]; + x2 = myinput[x-1]; + if polymer_d(x1,x2): + myinput = sub + myinput[x:]; + is_poly = True; + break; + else: + sub += x1; + return len(myinput); + +#part 2 +def ShortestPolymer(myinput): + inp_max = 999999; + inp_c = ""; + for c in range(ord("A"),ord("Z")+1,1): + subinput = myinput; + subinput = subinput.replace(chr(c),""); + subinput = subinput.replace(chr(c+cdiff),""); + subinput = polymer_strip(subinput); + if (len(subinput) < inp_max): + inp_max = len(subinput); + inp_c = c; + return inp_max + +f = open("05.in","r"); +cdiff = 32; +PuzzleInput = f.read().replace("\n",""); +f.close(); +p1 = PolymerReaction(""+PuzzleInput); +print("part 1", p1); +p2 = ShortestPolymer(""+PuzzleInput); +print("part 2 ",p2); + -- cgit v1.2.3