as soon as i saw this, i remembered the IntCode shenanigans from last year...can't wait til we're forking off 4 copies of this VM to run in parallel or talk to each other or whatever :)
ts solution was pretty compact here, although I got tripped up by the sneaky blank line at the end of the input! I've been doing this for a few years and we're 8 days in, you'd think I'd remember that by now haha.
hello! Sorry did not post yesterday as was visiting my mum in hospital, but completed day 7 this morning, which I have to say was a bit messy!
Day 8 on the other hand seems a lot of fun and I'm remembering more Haskel (and cateory theory) each new day. It's been a while :-) Anywhy, below is today's soloution(s). I did give into using Parser combinators as it just seemed simplier, but other than that it is all fairly standard.
-- anamorphism for lists, used to generate our program traces and modificationsunfoldr::(b->Maybe(a,b))->(b->[a])unfoldrfb=casefbofJust(a,b')->a:unfoldrfb'Nothing->[]-- our 3 known opcodesdataOp=NOpInt|AccInt|JmpIntderiving(Show,Eq)typeProgram=[Op]typePC=Int-- Simple parserlexer=Token.makeTokenParser(TP.emptyDef{Token.reservedNames=["nop","acc","jmp"]})reserved=Token.reservedlexer-- op codeinteger=Token.integerlexer-- integerwhiteSpace=Token.whiteSpacelexer-- whitespace-- parse individual opcodepOpcode::TP.Parser(Int->Op)pOpcode=(reserved"nop">>returnNOp)<|>(reserved"acc">>returnAcc)<|>(reserved"jmp">>returnJmp)-- parse an individual instructionpInstruction::TP.ParserOppInstruction=doop<-pOpcodewhiteSpaceop.fromIntegral<$>integer-- parse all opsparseOps::String->[Op]parseOps=either(error.show)id.TP.parse(TP.many1(whiteSpace>>pInstruction))""-- given a PC and a set of visited PC, have we been there before?halt::PC->DS.SetInt->Boolhalt=DS.member-- execute a single op, returning a new acc and a function to compute next PCexecuteOp::Op->Int->(Int,PC->PC)executeOp(NOp_)acc=(acc,(+1))executeOp(Accinc)acc=(acc+inc,(+1))executeOp(Jmpi)acc=(acc,(+i))-- step a single op for a given program, at PC, seen PCs, and current Accstep::(Program,PC,DS.SetInt,Int)->Maybe((Bool,Int),(Program,PC,DS.SetInt,Int))step(ps,pc,seen,acc)|pc>=lengthps=Nothing|otherwise=let(acc',next)=executeOp(ps!!pc)accpc'=nextpcinJust((haltpc'seen,acc'),(ps,pc',DS.insertpc'seen,acc'))-- modify an op (NOP => JMP and JMP => NOP), if possiblemodOp::Op->MaybeOpmodOp(NOpi)=Just(Jmpi)modOp(Accinc)=NothingmodOp(Jmpi)=Just(NOpi)-- generate a modified program, if possible, given a Program and PCmods::(Program,PC)->Maybe(MaybeProgram,(Program,PC))mods(ps,pc)=ifpc<lengthpsthenJust(maybe(Nothing,(ps,pc+1))aux(modOp(ps!!pc)))elseNothingwhereauxop=(Just(takepcps++[op]++drop(pc+1)ps),(ps,pc+1))-- produce all traces of a programs executionexecute::Program->[(Bool,Int)]executeps=unfoldrstep(ps,0,DS.empty,0)-- find acc at the point when a single op is executed twicepart1=snd.head.dropWhile(not.fst).execute-- find a acc for a modified program that terminatespart2=fromMaybe0.head.dropWhile(==Nothing).map(p.execute).foldr(\ab->maybeb(:b)a)[].unfoldrmods.(\ps->(ps,0))wherep[(False,v)]=Justvp((True,_):_)=Nothingp(_:xs)=pxs-- run task 1 and task 2 for AOC ay 8main=doops<-readFile"day8_input"<&>parseOpsprint(part1ops)print(part2ops)
Rust! I am doing WAY too much object copying. I think I could get the same results by passing vector of references around. But, wanted to not think too much :)
This was much more enjoyable after the utter faff that was day 7
defboot(bootcode):acc=0visited=set()pos=0whileTrue:ifpos>=len(bootcode):return(acc,True)ifposinvisited:return(acc,False)op,n=bootcode[pos].split(' ')n=int(n)visited.add(pos)ifop=="nop":pos+=1elifop=="acc":acc+=npos+=1elifop=="jmp":pos+=ndefswap_op(line):op,n=line.split(' ')ifop=="nop":op="jmp"elifop=="jmp":op="nop"# leave acc unaffected
return" ".join((op,n))#return "jmp" if op == "nop" else "nop"
deffix(bootcode):val,terminated=boot(bootcode)ifterminated:returnval,terminatedfori,linenumerate(bootcode):# don't modify the original
code_copy=[lforlinbootcode]code_copy[i]=swap_op(l)val,terminated=boot(code_copy)ifterminated:returnval,terminated#bootcode[i] = swap_op(l)
returnval,Falsebootcode=[r.strip()forrinopen('input.txt')]acc,term=boot(bootcode)print(f"Part 1: the original bootcode terminates {''iftermelse'ab'}normally with accumulator value {acc}")acc,term=fix(bootcode)print(f"Part 2: the fixed bootcode terminates {''iftermelse'ab'}normally with accumulator value {acc}")
My solution in C#
Tried to make it look decent with the Operation enum and an Instruction class:
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Linq;usingSystem.Text;namespaceAdventOfCode2020{enumOperation{nop,acc,jmp}classInstruction{publicOperationOperation{get;set;}publicintArgument{get;set;}publicboolIsExecuted{get;set;}}staticclassDay8{staticList<Instruction>Instructions=newList<Instruction>();staticintaccumulator=0;staticintinstructionPosition=0;//InstructionChanged is used to show which instruction had to be changedstaticInstructionInstructionChanged;publicstaticvoidExecute(){List<string>input=newList<string>(File.ReadAllLines("C:\\Users\\DirkFraanje\\Documents\\adventofcodeday8.txt"));//Added a imer just for funvartimer=newStopwatch();timer.Start();//First create a nice list of instructions from the inputfileforeach(varinstructionininput){Instructions.Add(CreateNewInstruction(instruction));}//Run recursive method to find the instruction that has to be changedFindInstructionToChange();//Stop the timer, show the answer and just for fun the instruction that has to be changedtimer.Stop();Console.WriteLine($"Answer: {accumulator} ");Console.WriteLine($"Instruction to change: {InstructionChanged.Operation} {InstructionChanged.Argument}");Console.WriteLine($"Executed in: {timer.ElapsedMilliseconds} milliseconds");}privatestaticvoidFindInstructionToChange(){vari=0;while(true){varinstruction=Instructions[i];switch(Instructions[i].Operation){caseOperation.nop:instruction.Operation=Operation.jmp;if(RunBootCodeSuccesful()){//Before returning the answer change the answer back to it's original Operation so it can be showed in the consoleinstruction.Operation=Operation.nop;InstructionChanged=instruction;return;}elseinstruction.Operation=Operation.nop;break;caseOperation.acc:break;caseOperation.jmp:instruction.Operation=Operation.nop;if(RunBootCodeSuccesful()){//Before returning the answer change the answer back to it's original Operation so it can be showed in the consoleinstruction.Operation=Operation.jmp;InstructionChanged=instruction;return;}elseinstruction.Operation=Operation.jmp;break;default:break;}i++;//Reset everything to it's defaultaccumulator=0;instructionPosition=0;Instructions.ForEach(x=>x.IsExecuted=false);}}privatestaticboolRunBootCodeSuccesful(){while(true){varinstruction=Instructions[instructionPosition];switch(instruction.Operation){caseOperation.nop:instructionPosition++;break;caseOperation.acc:accumulator+=instruction.Argument;instructionPosition++;break;caseOperation.jmp:instructionPosition+=instruction.Argument;break;default:break;}instruction.IsExecuted=true;if(instructionPosition>Instructions.Count-1)returntrue;varnextInstruction=Instructions[instructionPosition];if(nextInstruction.IsExecuted)returnfalse;}}staticInstructionCreateNewInstruction(stringinstructionline){varinstruction=newInstruction();varsplitOperationAndArgument=instructionline.Split('');switch(splitOperationAndArgument[0]){case"nop":instruction.Operation=Operation.nop;break;case"acc":instruction.Operation=Operation.acc;break;case"jmp":instruction.Operation=Operation.jmp;break;default:break;}instruction.Argument=int.Parse(splitOperationAndArgument[1]);returninstruction;}}}
I spent longer than I care to admit trying to figure out the best way to access/use the data from the initial input in a mutable way: I started with returning the Program from the input parser, but nothing could be mutable that way; I tried boxes, I tried Rc, (both of which I haven't really played around with before); finally settled on making them Clone-able and just duplicating it for the run.
There's some control flow stuff in here that I'm sure there are better ways of solving (if you know or have a suggestion, please drop it in!).
Also gave me nightmares of last year's opcode parser... π±
I think the insight you need is to separate the mutable from the immutable state. The program is immutable (except for the modifications in part 2) but the machine state is mutable. The instructions are immutable but the record of visiting them is mutable. Cloning the whole program and changing one instruction is the right approach however. Good work!
defexecute_program(lines):lines_executed=set()cursor=0accumulator=0defacc(lines,cursor,accumulator):return(cursor+1,accumulator+int(lines[cursor][1]))defjmp(lines,cursor,accumulator):return(cursor+int(lines[cursor][1]),accumulator)defnop(lines,cursor,accumulator):return(cursor+1,accumulator)terminated=Falsewhilenotterminatedandcursornotinlines_executed:instruction=lines[cursor][0]lines_executed.add(cursor)operations={'jmp':jmp,'acc':acc,'nop':nop,}operation=operations[instruction]cursor,accumulator=operation(lines,cursor,accumulator)# Terminate if end at program
terminated=cursor==len(lines)returnterminated,accumulatordefpart1(lines):_,result=execute_program(lines)returnresultprintpart1(lines)defpart2(lines):foriinrange(len(lines)):# Copy lines so that changes don't persist.
local_lines=[xforxinlines]# Switch statement jmp/nop
if'jmp'inlocal_lines[i][0]:local_lines[i]=('nop',local_lines[i][1])elif'nop'inlocal_lines[i][0]:local_lines[i]=('jmp',local_lines[i][1])terminated,result=execute_program(local_lines)ifterminated:breakreturnresultprint"Solution part 2: %d"%part2(lines)
My solution for day 08, where I have tried to make it easy to extend. Just in case we have to continue building on this another day π¬ (getting some intcode flashbacks from 2019...)
require'set'instructions=[]File.readlines('08.txt').eachdo|line|code,argument=line.split(' ')instructions.push[code,argument.to_i]endacc=0i=0visited=Set.newuntilvisited.include?icode,argument=instructions[i]visited.addicasecodewhen'nop'# Do nothingi+=1when'acc'acc+=argumenti+=1when'jmp'i+=argumentendendputsacc
require'set'instructions=[]File.readlines('08.txt').eachdo|line|code,argument=line.split(' ')instructions.push[code,argument.to_i]endswap_indices=instructions.each_with_index.selectdo|instruction,i|code=instruction[0]code=='nop'orcode=='jmp'end.mapdo|instruction,i|iendswap_indices.eachdo|j|acc=0i=0visited=Set.newnew_instructions=Marshal.load(Marshal.dump(instructions))ifnew_instructions[j][0]=='jmp'new_instructions[j][0]='nop'elsenew_instructions[j][0]='jmp'enduntilvisited.include?icode,argument=new_instructions[i]visited.addicasecodewhen'nop'# Do nothingi+=1when'acc'acc+=argumenti+=1when'jmp'i+=argumentwhennil# Stepped out of instructions arrayputsaccbreakendendend
Writing today's solution went pretty fast. But oh man, it takes longer and longer to write these step-by-step tutorials. I'll have to see whether Lifeβ’ allows me to continue this until Xmas:
I'm a Staff Software Engineer at Cisco. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
Had a much better time today. I'm very happy with how this came out.
#include "Day8.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "parsing.h"
/// Day 8: Handheld Halting/// /// Figure out how to break a handheld game out of an infinite loop!/// The type of operation that is usedtypedefenum{OP_NOP,///< No operationOP_ACC,///< Adjust acc by argOP_JMP,///< Jump to arg location, relative to current ip}Opcode;/// A full instruction line in the programtypedefstruct{Opcodeop;///< The operation to be doneintarg;///< A positive or negative integer argument}Instruction;/// A program that keeps track of whether it has already run codetypedefstruct{Instruction*program;///< List of instructions to be runintip;///< Index of the current instruction to runintacc;///< Acc value adjusted by the acc opcodeintlines;///< Number of lines in the programbool*line_run;///< List of booleans denoting whether each line has run yet}Interpreter;/// Check if the current line has already been run#define HAS_ALREADY_RUN(interp) (interp.line_run[interp.ip])
/// Label this line as already run#define MARK_AS_RUN(interp) (interp.line_run[interp.ip] = true)
/// Create a new interpreter from an input filestaticInterpreternew_interpreter(constchar*filename){FILE*fp;fp=fopen(filename,"r");if(fp==NULL){printf("Couldn't open input file.\n");exit(EXIT_FAILURE);}Interpreterinterpreter;intlines=count_lines(fp);Instruction*program=(Instruction*)malloc(sizeof(Instruction)*lines);for(inti=0;i<lines;i++){charop[4]={0};intarg=0;fscanf(fp,"%s %d\n",op,&arg);Instructioninstruction={0};switch(op[0]){case'n':instruction.op=OP_NOP;break;case'a':instruction.op=OP_ACC;break;case'j':instruction.op=OP_JMP;break;default:printf("Unrecognized opcode %s.\n",op);exit(EXIT_FAILURE);}instruction.arg=arg;program[i]=instruction;}fclose(fp);interpreter.ip=0;interpreter.acc=0;interpreter.lines=lines;interpreter.line_run=(bool*)malloc(sizeof(bool)*lines);memset(interpreter.line_run,0,sizeof(bool)*lines);interpreter.program=program;returninterpreter;}/// Free an interpreter's malloced memoryvoidfree_interpreter(Interpreter*interpreter){free(interpreter->program);interpreter->program=NULL;free(interpreter->line_run);interpreter->line_run=NULL;}/// Run the instruction under the IPvoidtick(Interpreter*interpreter){Instructioninstruction=interpreter->program[interpreter->ip];switch(instruction.op){caseOP_NOP:interpreter->ip++;break;caseOP_ACC:interpreter->acc+=instruction.arg;interpreter->ip++;break;caseOP_JMP:interpreter->ip+=instruction.arg;break;}}/// What is the value of the acc when the first loop is encountered?intpart1(constchar*filename){Interpreterinterpreter=new_interpreter(filename);while(true){if(HAS_ALREADY_RUN(interpreter)){returninterpreter.acc;}else{MARK_AS_RUN(interpreter);}tick(&interpreter);}}/// Makes a standalone copy of an interpreterInterpretercopy_interpreter(Interpreter*orig){Interpreternew;new.ip=orig->ip;new.acc=orig->acc;new.lines=orig->lines;new.line_run=(bool*)malloc(sizeof(bool)*new.lines);memcpy(new.line_run,orig->line_run,sizeof(bool)*new.lines);new.program=(Instruction*)malloc(sizeof(Instruction)*new.lines);memcpy(new.program,orig->program,sizeof(Instruction)*new.lines);returnnew;}/// If you change one of the JMP to a NOP or vice versa, the program/// will exit normally. When it actually does that, what is the/// value in acc?intpart2(constchar*filename){Interpreterbase=new_interpreter(filename);for(inti=0;i<base.lines;i++){if(base.program[i].op==OP_ACC)continue;Interpreterinterpreter=copy_interpreter(&base);if(interpreter.program[i].op==OP_JMP){interpreter.program[i].op=OP_NOP;}else{interpreter.program[i].op=OP_JMP;}while(true){if(HAS_ALREADY_RUN(interpreter)){break;}elseif(interpreter.ip>=interpreter.lines){returninterpreter.acc;}else{MARK_AS_RUN(interpreter);}tick(&interpreter);}free_interpreter(&interpreter);}return-1;}/// Run both days.intday8(){printf("====== Day 8 ======\n");printf("Part 1: %d\n",part1("data/day8.txt"));printf("Part 2: %d\n",part2("data/day8.txt"));returnEXIT_SUCCESS;}
I solved Part 2 in python but uh... in a slightly unconventional way. I re-wrote the CPU so that it used Redis for memory instead of variables, wrote functions so it could operate one cycle at a time every time the script was run, built it into a Docker image, and pushed it to a registry, and then wrote an Airflow DAG to orchestrate running of the CPU inside a kubernetes cluster.
And then had it brute-force the solution by running it one cycle per Kubernetes Pod, deployed by Airflow, until it found the answer and sent it to me via Slack.
I'm a Staff Software Engineer at Cisco. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
I knew Rust would shine for the machine simulations. Let's hope for more of these.
Full code
Python!
as soon as i saw this, i remembered the IntCode shenanigans from last year...can't wait til we're forking off 4 copies of this VM to run in parallel or talk to each other or whatever :)
ts solution was pretty compact here, although I got tripped up by the sneaky blank line at the end of the input! I've been doing this for a few years and we're 8 days in, you'd think I'd remember that by now haha.
hello! Sorry did not post yesterday as was visiting my mum in hospital, but completed day 7 this morning, which I have to say was a bit messy!
Day 8 on the other hand seems a lot of fun and I'm remembering more Haskel (and cateory theory) each new day. It's been a while :-) Anywhy, below is today's soloution(s). I did give into using Parser combinators as it just seemed simplier, but other than that it is all fairly standard.
Rust! I am doing WAY too much object copying. I think I could get the same results by passing vector of references around. But, wanted to not think too much :)
This was much more enjoyable after the utter faff that was day 7
My solution in C#
Tried to make it look decent with the Operation enum and an Instruction class:
Rust solution.
I spent longer than I care to admit trying to figure out the best way to access/use the data from the initial input in a mutable way: I started with returning the Program from the input parser, but nothing could be mutable that way; I tried boxes, I tried Rc, (both of which I haven't really played around with before); finally settled on making them Clone-able and just duplicating it for the run.
There's some control flow stuff in here that I'm sure there are better ways of solving (if you know or have a suggestion, please drop it in!).
Also gave me nightmares of last year's opcode parser... π±
As always, on Github.
I think the insight you need is to separate the mutable from the immutable state. The program is immutable (except for the modifications in part 2) but the machine state is mutable. The instructions are immutable but the record of visiting them is mutable. Cloning the whole program and changing one instruction is the right approach however. Good work!
Python
My solution for day 08, where I have tried to make it easy to extend. Just in case we have to continue building on this another day π¬ (getting some intcode flashbacks from 2019...)
COBOL. I'm struggling... nothing yesterday and only part 1 today
Well this felt a lot easier than yesterday... Looking forward to see whether we're going to be expanding on this one in the coming days...
BootSequence
Part1
Part 2
More javascript, less regex. I get the feeling that I'm going to have to give up on my regex quest.
Here's my solution for part 2 in Elixir. It shares most of its code with part 1, so I don't think it's all that interesting to share both.
Another OOP solution in Ruby.
Ruby, part 1:
Ruby, part 2:
Writing today's solution went pretty fast. But oh man, it takes longer and longer to write these step-by-step tutorials. I'll have to see whether Lifeβ’ allows me to continue this until Xmas:
[Advent of Code 2020] Day 8 Step-by-Step Tutorial (TypeScript)
Kai γ» Dec 8 γ» 9 min read
Had a much better time today. I'm very happy with how this came out.
I solved Part 2 in python but uh... in a slightly unconventional way. I re-wrote the CPU so that it used Redis for memory instead of variables, wrote functions so it could operate one cycle at a time every time the script was run, built it into a Docker image, and pushed it to a registry, and then wrote an Airflow DAG to orchestrate running of the CPU inside a kubernetes cluster.
And then had it brute-force the solution by running it one cycle per Kubernetes Pod, deployed by Airflow, until it found the answer and sent it to me via Slack.
Blog: dev.to/meseta/advent-of-code-day-0...
Omg youβre a hero. This is so very impressive
My Javascript walkthrough: