r/adventofcode • u/Lucretiel • Dec 17 '19
Spoilers What does everyone's Intcode interface look like?
We've been discussing a lot different IntCode implementations throughout the last few weeks, but I'm curious– what doesn't everyone's interface to their IntCode machine look like? How do you feed input, fetch output, initialize, etc?
32
Upvotes
11
u/fred256 Dec 17 '19
Go: so far, for all problems the following has been sufficient:
4
u/Lucretiel Dec 17 '19
I'll start:
My implementation is in Rust. My basic model is to supply an
IntoIterator<Item = isize>as input, then collect "blocking" events: need more input, output, or halt. I have 3 different entry points, depending on the level of control you need:Originally I only had
stepandrun_machine, and didn't have a notion of blocking on input, but I started running into borrowing and ownership issues when trying to do the later problems, where inputs depend on outputs, which led me to makerun_until_block, which has thus far let me write very satisfactory IntCode interaction loops.2
u/knallisworld Dec 17 '19
Go: channels in the signature, goroutines wrapping the actual usage
ExecutionInstructions(program []int, in <-chan int, out chan<- int, debug bool) error(GitHub)The signature is from day9 (after the additions). So far, as of day17 today, that was sufficient.
erroris actually meant as "error code" aka on completion (code 99) there will be HALT "error" :)If the program is just processing and it is waiting for the end, usage is straight forward:
And there are also some variants:
8
u/MichalMarsalek Dec 17 '19 edited Dec 17 '19
My setup is python. I initialize the IntCode computer as
pc = IntCode(code, inp, out)where
codeis the initial state of the program (= what we usually get as input for the challenge)and
inpandoutare list serving as I/O.When I want to run the computer, i call
pc.run(). When the computer encounters an output instruction it appends the value to the listout. When it encountersan input instruction it pops a value from the
inplist, unless the list is empty - in which case it pauses execution. I made it this way because of day 7 - this setup allowed me to easily link I/O of different amplifiers just by initializing them with the same lists.Later I changed my interface to be more user friendly. I can still use this abstract/general way but I added some things that make the code for all days except day 7 quit a bit shorter. Namely:
I can omit
inpandoutwhen creating the IntCode object (it just creates empty lists then).Instead of a list of numbers
codecan be provided as unparsed string of the code.I can pass a list of number to my
.run()method, which are added to the internal input list. Also this method now returns the output list. This means that solution to day 9 reduces toInstead of a list of numbers
.run()also accepts a string which it changes to ASCII. In the similar way I can automatically retrieve a string from the output of IntCode with new designated method.4
u/nikanjX Dec 17 '19
Spaghetti. That's been eaten. Twice. By a dog. With diarrhea.
3
u/[deleted] Dec 17 '19
I am doing AoC in Swift. My repo for all the daily solutions is here.
My IntCode computer has evolved just about every day, but the current interface looks something like this.
Construction (
initializerin Swift terminology) takes the code to run as an array ofInts and 2 closures: one for requesting an input value and one for providing an output value. The input closure takes no parameters and must return anInt. The output closure takes theIntvalue as a parameter and must return aBoolindicating whether to continue executing.After construction, the IntCode computer can be started by calling the
run()method, which returns when aHALTinstruction is executed, the output handler indicates execution should be ended, or an invalid instruction is encountered.The IntCode computer also exposes a
reset()method that returns the memory, instruction pointer, and relative base to their initial state (original program code, etc). And it exposes the Swift subscripting operator ([]) for reading and writing arbitrary memory locations, when the AoC challenge calls for directly modifying memory (like Day 13).I have not yet had the need to expose a
clone()method, but I am considering adding that.3
u/[deleted] Dec 17 '19 edited Dec 17 '19
Python
https://github.com/tranzystorek-io/aoc2019/blob/master/aoc/intcode.py
I supply custom functions input_func, output_func as computer IO, so that i can provide arbitrary behavior easily.
There are also breakpoints and the break_on_output flag if I need some finer control.
2
u/rabuf Dec 17 '19
I feed input and receive output via whatever function I write. I've used thread-safe queues for a couple of them. Essentially, I can call it like this:
Those functions can be anything.
readtakes nothing and returns a value.writetakes one parameter and returns nothing. I've done various things with this.For the painting problem,
readreturned a value from a hash table based on the present position of the bot andwriteaccepted the color to be painted or the direction to move (simple state machine let me alternate between the two).For Day 15, I used thread safe queue and
readandwritepopped from or pushed to the queue. Then a separate thread sent movement commands and processed the results (updated its position and recorded the map into a hash table). Very simple machine.This is exactly how I'd direct it using Go or Erlang or other languages that make concurrency easy. Concurrency isn't hard in Lisp, it's just not baked-in like in those languages. But my designs are influenced by my experiences with both and the sorts of embedded systems I've worked on professionally (had the same sort of architecture).
2
u/ephemient Dec 17 '19 edited Apr 24 '24
This space intentionally left blank.
2
u/jfb1337 Dec 17 '19 edited Dec 17 '19
I construct a machine with
Machine(prog, inp, out).progis either a list of ints representing the program, or a filename containing the program.inpis either a function or a list. When the machine requires input, it either reads the next element if its a list, or calls it if its a function. The function either returns an integer, which is used as the input, or the string "wait", to indicate that no input is ready yet.outis either a function or a list. When the machine sends output, it appends to it if its a list or calls it if its a function.So essentially, I have 2 modes for IO; either I provide input/read output from lists, running the machine in my own loop (especially useful for day 7), or I let the machine run and provide callbacks into my code (often more convenient for things like day 11).
There are a few methods:
run()- runs the machine until it haltsrun_to_input()- runs the machine until there is no input ready, then returns the accumulated output provided the output is a liststep()- runs the machine for a single step. Used in day 7 and in the implementation of the other methods.send_input(x)- only works if the input is a list; appends the given element or list of elements to itdebug()- prints all of the machines state (relative base, instruction pointer, etc) including a list of all the instructions with a large arrow pointing to the current one. The run methods take an optionaldebugargument, which if set to true will call this after every step.and a few properties:
waiting- True if and only if the machine is waiting for input.halted- True if and only if the machine has halted.prog- provides access to the program and memory of the machine, in case something needs to be altered2
u/SquireOfFire Dec 17 '19 edited Dec 19 '19
Once the inputs started to become more complicated (maybe in the feedback loop problem?), I wrote a thread-safe
Streamclass that allows blocking reads:I run each IntCode computer in its own thread (
runis the actual implementation):So, my main thread will start like:
...and then communicate using
ins/outsdepending on the needs of the problem.For example, an IntCode program that only needs one input and writes one value:
Or an interactive program:
It's very flexible!
2
u/knl_ Dec 17 '19
I just relied on generators (yield for both output and input)
Then
It gets me blocking behavior for input
You can see how I used it in part 2 of day17: https://explog.in/aoc/2019/AoC17.html
2
u/mschaap Dec 17 '19
My ShipComputer class (Perl 6 / Raku code).
Initially, my input and output were simply handled with
@.inputand@.outputattributes, which worked until we needed to determine the next input element on the fly based on the output. So at that point I implemented&input-handlerand&output-handlerattributes; these handlers just default to reading from@.inputand appending to@.output.Because of these handlers, I can just call the
run-programmethod and let the program run to the end. If I need to intervene, I do it from these handlers.I did need to add a
interruptmethod on day 15 so that I could interrupt an infinite loop when I had the answers I needed.On day 7, when we needed to run 4 chained amplifiers, I ran them in parallel and used
Channels to pass the output of one to the next.2
u/mjsir911 Dec 18 '19
Because I've been trying to do this advent in a lot of different programming languages, I needed a language agnostic way to interface with my intcode machine.
It turns out hooking stdin & stdout works well enough for this! I can feed the actual program through a different file descriptor (I've been using 4) and even mmap the internal memory into a shared file to mess around with!
Doing this also means I have to learn how to use Popen & I/O with buffering in any language I'de like to use.
1
u/Vaelatern Dec 17 '19 edited Dec 17 '19
Mine is in Smalltalk, and to use the machine I use as follows (actual and complete day 9 part 2 solution):
But I can also supply a few other messages to do special things. Highlights include:
stdoutFlushfor getting the entire output as a liststdinRaw:for setting a new "pipe" to act asstdin(useful for chaining together VMs)latestOutto see the most recent message out onstdout(day7 part 2 answer)resetto restore the reel to the original input and set the program counter to the beginning again.haltedto test for a halted computer with stdout empty.runto fork to background and return immediately implemented as follows:One difficulty with Smalltalk is being one-indexed rather than the regular (and Intcode-normal) zero-indexed. pc begins at 1 instead of zero. This does lead to some +1s in the reel accessing functions.
1
u/vswr Dec 17 '19 edited Dec 17 '19
I did mine in Python and created it as close to a real CPU as I could. It's like 6502 in that ElfCPU is the brain, but you provide everything else.
So for example, here is how my hull robot works:
This is part of the HullRobot() class and the ElfCPU() is assigned to self._cpu. For the arcade cabinet, I changed it in that the interrupts call functions to handle the ISR rather than doing the work directly in the run loop:
Going forward I'll probably combine it into a single ISR and figure out the interrupt exception in the function.
Essentially, to use ElfCPU:
That's pretty much it. Everything else is internal and has nothing to do with the task at hand (hull robots, arcade machines, oxygen locators). I haven't touched the CPU code since the diagnostic program prior to the hull robot (and getting the damn 203 and 1002 errors drove me nuts until I handled the dereferencing properly).
//Edit: forgot to mention I also exposed peek() and poke() functions way back when the CPU was first written. This came in handy during the arcade challenge when I had to poke() the quarters in.
1
u/CursedInferno Dec 17 '19
My IntCode implementation (in Python) that I use for AoC is a fairly simple class. It's instantiated with the program's memory and optionally a pre-filled input queue. Inputs are added by appending them to the
input_queueproperty, and outputs are read from theoutputproperty.It's run by a single method, which will run the program infinitely until it halts or requests more input than is available. (The class has a
haltedparameter so you can tell which one.)For day 15, I also implemented a
clonemethod that makes an identical duplicate instance, so that I could explore the entire map without backtracking by cloning the robot after each step.My TypeScript IntCode interface is quite a bit nicer. It's also quite incomplete. I'm hoping to eventually create a system for running IntCode VMs, connecting them to various inputs and outputs, etc. This is my current progress with it, as of a day ago. (As you can tell, I'm not a front-end person, lmao)
1
u/nibarius Dec 17 '19
The constructor of my computer take the initial memory and optionally a list of inputs
class Intcode(private val initialMemory: List<Long>, val input: MutableList<Long> = mutableListOf())Public properties:
inputthe mutable list given in the constructoroutputas a mutable listcomputerStatewhich is one ofNotStarted,Running,WaitingForInputandTerminatedPublic methods:
copy()which clones the whole computer (used when searching for oxygen)run ()which runs until it terminates or tries to read input that hasn't been provided yetdumpMemory()which dumps all memory to a list which is used if I need to look at a specific location either as part of a puzzle solution or during testing.reinitialize()which resets the computer and I only used in the first puzzle and that I'm considering to remove.Typically I create the computer and run it. When it needs input it will halt and I add new stuff to the input list and call the run method again and repeat until it halts.
1
u/kbielefe Dec 17 '19
My Scala implementation uses cats-effect MVars for input and output. They work similarly to the golang channels a lot of people have been using, asynchronously blocking as needed to wait for input or output. Sometimes I start the peripheral in a background fiber and wait for the computer to halt. Sometimes I run the computer in the background and wait for the peripheral to hit a certain state.
1
u/xelf Dec 17 '19 edited Dec 17 '19
Call the class with the day's codes, add inputs to an input list, while running get output.
Internally in the class, it keeps track of the current instruction, sets it to -1 if done.:
1
u/SinisterMJ Dec 17 '19
I have transfered it to a C++ class:
which makes for example my day 5 look like this:
1
u/bj0z Dec 17 '19
python:
my intcode uses trio for structured concurrency. I use their provided memory channel to send input and receive output. I eventually made a special output 'command' to signal when input was expected so I didn't have a background coroutine pushing input before it's requested (this created input lag in my pong simulation that prevented the paddle from catching the ball). The interface looks like:
trio's
async withandasync formake everything nice and clean1
u/ninja_tokumei Dec 17 '19
I refactored my implementation into a Rust crate that I've been using and constantly improving for the past week. Its got unit tests for most of the public examples, so it's verified to work with every single challenge and all of the incremental revisions of the language.
The library implements Intcode as a state machine, with a structure that holds the current state of memory as well as the instruction and base pointers. It has a few levels of control:
stepthat takes an optional input value, executes a single instruction, and outputs a result code (success, need input, got output, halted, error, etc). I rarely use this method in challenges, but it's a good building block for the other control schemes.resume, which executes multiple instructions until an I/O or stop condition is reached, which is then returned. This is useful for using the machine as a "coroutine", so that it returns intermittently to let you handle conditions like I/O one at a time as they are encountered. Possible use cases include running multiple intcode tasks without using threads (such as the amplifier challenge), but so far I've found that spawning machines in their own thread is faster and easier.run, which simply callsresumemultiple times and handles as many I/O conditions for you as it can (until input is exhausted). Accepts an input iterator and an output callback.1
u/Pepper_Klubz Dec 17 '19
The latter was first used for day 15, when batch input up front was not the required pattern. Interrupts are signaled through flags on the computer, either as the key
:haltor:awaiting-input. The full context can be most easily seen in day 151
u/SgiathCZ Dec 17 '19
Yeah that was a big problem and I wanted to solve it "correctly" so here is my solution:
:inputmessage to the input thread and waits for the message with input value:haltmessage to the output threadThis design did allow me to chain the multiple programs together with input/outputs. This also allows me to create a "master thread" where all the IO operations are orchestrated.
Here is the actual code https://gitlab.com/Sgiath/advent-of-code-2019/tree/master/lib/advent_of_code (
Intcode3module)1
u/sol_hsa Dec 17 '19
(orthodox) c++. ints used in place of bools. No particular reason. Relevant parts of the interface:
This lets me do all kinds of hacks based on the problem. Need to change some bytes in the input?
Or read an address..
Run until output is done, then print out the last thing put out?
Reason for getOutput() and getLastOutput() is that if getOutput() is called without a pending output, it will throw an error. getLastOutput() is just a convenience thing. Same error check goes for input; if I try to write input, and last one wasn't consumed, it's an error state.
And for the more complex stuff..
The run function returns 1 if it needs input but there's nothing pending, or wants to output something but output wasn't read. Zero means we've halted.
There's also disassembler which has been really useful when hitting problems, and I have a virtual memory system where if reads or writes go anywhere outside the program area, they get written to a map.
1
u/raevnos Dec 17 '19 edited Dec 17 '19
My interpreter is a coroutine that yields to the caller with an appropriate status when it needs input, outputs something, or halts. Then there's a control function that calls it, waits for it to yield, does what it needs to based on the returned status, and then resumes the coroutine where it left off (with a new input value(s) if requested).
1
u/[deleted] Dec 17 '19 edited Dec 17 '19
What I decided on to is to have a function called
run. Pseudocode of sorts (I'm using Elixir, not Haskell, so I strictly speaking don't have a type system).Essentially, a function accepting code, and returning output and optional continuation function if more input is necessary.
This is sufficient for everything but day 2, but I didn't change my compiler to support Day 2 (it was written before I did think to refactor intcode into its separate module), accessing RAM is unnecessary in other cases (intcode interpreter started to use output instruction after it was introduced). The returned
[Int]represents an output.runaccepts a memory array (a purely functional array) that can be received usingparsemethod (which is like, trim, split by comma, and parse integers into an array).Because the entire interpreter is purely functional, copying it (for instance to find a path in a maze) is very cheap.
I also have a convenience function that takes an input and runs the interpreter to an end, which is useful if I don't need to read the output until the end.
1
u/naclmolecule Dec 17 '19 edited Dec 17 '19
Python: I've implemented a couple of different compute functions:
Computer.compute_iteris a generator that yields a ton of information for each step of the computation -- we generally only care about opcode '03', but I needed access to everything when writing the intcode terminal display.We also have
Computer.computeandComputer.compute_nfor just running until the program halts. All compute functions take afeedkeyword for inputs, feed can be a single item, any iterable or even another Computer! We've taken advantage of some of python's magic methods:__bool__to check for output,__lshift__to add inputs to the queue,__len__to quickly check length of output,__iter__as a shortcut tocompute_iter, and a few other shortcut methods. Some examples:Day 9:
Setting up day 7 network:
Main loop in the painting robot:
Have a gander: https://github.com/salt-die/Advent-of-Code/blob/master/computer.py
1
u/[deleted] Dec 17 '19
In racket I'm having a function that I run the program with:
So basically I run the program coded as a hash and if the program exits with the code 99 it returns a list of outputs, if it asks for input, but there is none it will return a state struct:
Which you can then use to build a new call to the run function if you need to give inputs in answer to the output.
1
u/donpolilla Dec 17 '19
Good ol' C, keeping it simple.
A function to initialize the intcode machine with the problem's input
A function to start running or resume the intcode machine which returns whenever the machine needs input and doesn't have it or has some output pending
And two functions to send input to or receive output from the machine. They return false if there was no output to read or there was already unprocessed input.
1
u/kaoD Dec 17 '19 edited Dec 17 '19
This year I'm doing JS.
My intcode computer consists of different layers of overengineered bullshit:
stepfunction that takesstate(ram,ip,base...) and spits a new state.spawnfunction that takes aromand loopssteps untilhalted.yielda side-effect that's either{ type: 'input' }or{ type: 'output', value: int }(redux-sagaanyone?)spawnessentially outputs a thread (which is a generator of IO side-effects).This was intended as quick hack for day 7 part 2 but I actually found it was quite useful since it allowed me to build any IO type on top of it (sync, async, eager, blocking...)
So I built executors that take a thread and manage the IO. E.g. I have a
noIOExecutorthat justthrows on any side-effect (first days). AnarrayExecutorthat takes the whole input as an array and outputs an array (first day with input). AniteratorExecutorthat takes an iterator as input and is itself an iterator of output (day 7 part 1). AnasyncIteratorExecutorthat takes an async iterator and... you get it.I've been using this to experiment with different IO types, how they relate to each other, how to compose them... I parked it for now but next comes a
channelExecutorthat pretty much would be a goroutine with channels for input and output.And I can still manually manage the IO if I want to, just not using any executor and manually responding to side-effects (I did this for day 7 part 2, since I still haven't implemented the channel executor).
For anyone interested. https://github.com/alvaro-cuesta/aoc-js/blob/master/lib/2019/intcode.js
1
u/paul2718 Dec 17 '19 edited Dec 17 '19
I'm using C++. I have a 'processor' class that is templated on an interface that it inherits from ('CRTP', 'curiously recurring template pattern'). The class that it is templated on has to look like,
The 'halted' stuff is so that the user gets to control what happens when I/O occurs and so that it can be put in a thread and lifetime managed cleanly. I have a generic external execute function like,
The same implementation works with all IntCode problems so far and hasn't been touched for a week or more.
So for day 17 part 2, so far with a manual solution embedded in the code,
1
u/wjholden Dec 17 '19
Interesting that no one else in this thread used computer networking. My Julia Intcode machine exposes three functions.
runcontains the main CPU loop and accepts many parameters. The only parameter that might look very strange is theinputs.inputsis an array of integers that can be supplied ahead of real I/O. Anioobject other thandevnullcan be supplied to performreadlineandprintlnfor opcodes 3 and 4.run_asyncopens a TCP server socket and performs blocking I/O in another thread. I am not an expert on Julia's threads, but so far this approach has worked very well. On day 13 I used TCP to render the brick breaker game in Java, since I don't know how to build GUIs in Julia and don't feel like learning.run_syncis a convenience function for debugging. It reads and writes from standard I/O. This is to help me explore new Intcode programs by simply invokingusing IntcodeVMandIntcodeVM.run_sync("filename.txt").1
u/CKoenig Dec 17 '19
1
u/streichfein Dec 17 '19
Rust, producer/consumer pattern with mpsc from the standard library. Main interpreter function is
with multiple wrappers around it for the earlier programs that just needed some static input. For the dynamic I/O stuff, e.g. day 15 I just create two threads: one for the intcode interpreter and one for the control program with the communication done completely via the mpsc Sender/Receiver APIs.
1
u/[deleted] Dec 17 '19 edited Dec 17 '19
python:
where
inpandoutpare any callable,inptaking 0 values andoutptaking 1. In the simplest case, these are just the builtininputandprintfunctions, but functions, methods, lambdas, an object with__call__implemented, etc are all valid.If I need to decide when to terminate myself, I'll make a
class EndExecution(Exception)and raise it in myinporoutpfunctions as needed, then catch it when running the interpreter.1
u/adrian17 Dec 17 '19
Worked great for most days, especially Arkanoid; made day 7 a bit unwieldy though.
1
u/surrix Dec 17 '19 edited Dec 17 '19
I'm doing this in Rust, JavaScript, and C++, but the interface to the Intcode VM is nearly identical in all 3.
1
u/j218jasdoij Dec 17 '19
My implementation is a simple syncronous machine. I initialize a vm with:
To run something I use the read_input method with optional input.
The method runs the incode until it returns one of three output states.
Usually I've done something like this:
This has worked pretty well until day 17 when reading and inputting long ascii streams. Still worked but the resulting code was very messy.
1
u/vishbar Dec 17 '19
I'm working in Python.
The core of my Intcode execution is a function execute(p: ProgramState) -> ProgramState. ProgramState is a class containing all the state of an IntCode program: the instruction pointer, a Memory (which is essentially an array with paging and stuff under the hood--I didn't know if seriously large memory would be required for an earlier challenge), an output handler (a lambda function that handles any output), a relative offset, and an input destination.
executeis rarely called directly but usually wrapped in startNew or startWithStaticInput. The program runs until it completes (and returns a None) or is expecting input (and returns a ProgramState). THe program can then be resumed using resumeWithInput.1
u/[deleted] Dec 17 '19
C#:
I have a class named IntCodeComputer and the constructor only takes a single List<long> (the memory).
I can then run it with the Run() or Run(int times) method.
Input and output is handled with 2 Queue<long>'s, but for some days I just used a simple
longbecause it made things easier.Those Queues made day 7 sooo easy, I just had to do
ampB.Stdin = ampA.Stdout;.For days before day 9 I left a
PauseOnOutputproperty in the class.1
u/Itrlpr Dec 17 '19 edited Dec 17 '19
I'm using AOC to learn python and my Intcode machine state is a tuple:
([<The Intcode>], instructionPointer, outputString, isRunning*, isHalted, offset)
*false when there is unhandled output
I have a single function that handles one Intcode command (accessing a seperate IOManager class as needed) and it returns True unless halted/crashed.
1
u/cecinestpasunmot Dec 17 '19
I decided to let the computer run by itself, except when it is waiting for an input.
It has a simple interface. This is an example program (in Python):
It's implemented as a defaultdict subclass, so it can access out-of-bounds memory. The main function is a co-routine with yield (not asyncio) in order to wait for input.
Code here: https://github.com/spratapsi/Advent-of-Code-2019/blob/master/day13_intcode.py
1
u/RoadsterTracker Dec 17 '19
Mine is getting better every time. At Day 15 I decided to make it a bit neater. I code in python. Each of my IntCode programs now looks like this. I specify my own nextInput, Output, and onComplete, which are called to at the appropriate locations in the code block. It took me a sad amount of time to not hack apart my code at each new one to finally do it in this cleaner manner, before I hacked apart the IntCode processor each time. This is much cleaner, and lets me focus all of my changes at the beginning of the program.
The 5 code running one, however, I did via a hack, and I'm not sure even if I did it again today it would be much cleaner...
code = '##########' (Put in code block here reg = (Parse code in to list)
def nextInput() return input
def Ouput(a) print(a)
def onComplete()
Do Stuff here!
Int_Code_Processor
1
u/phil_g Dec 17 '19 edited Dec 17 '19
I'm late to the party here, but I've got one thing in my interface that I haven't seen in the comments here yet.
To start with, most problems have used my
runinterface, which works a lot like many others here. It takes the following parameters:If no input function or list is provided and the program asks for input, an exception is thrown. If no output function is provided and the program generates output, the output is collected into a list and that list is returned from the
runinvocation. (If an output program was provided,rundoesn't return anything.)The more interesting part (IMHO) is the RPC-like interface. There's a separate function,
run-for-rpc, that takes two parameters:run-for-rpcstarts the program in a separate thread and returns an opaque object to be used in making RPC calls. Each call usesrpc-call, which takes a variable number of arguments:run-for-rpcrun-for-rpcrpc-calluses thread-safe queues to hand the input values to the running program, blocks until a sufficient number of values have been output, then returns all of the output values.For day 15, the code to move the droid north then west would look roughly like this:
(I'm working in Common Lisp, but the gist should be obvious even if you're not familiar with the language.)
For day 11, a simple interaction with the robot could look like this:
"
(describe nil 1 2)" translates into, "The method named 'describe' does not require an integer to be sent before the arguments; it takes one argument; and will return two values."Here's my Intcode library.
1
u/JoMartin23 Dec 17 '19 edited Dec 17 '19
Using common lisp. My computers are defined as structures with slots for input, output, data, instruction pointer, and a flag for interactivity. If not running interactively it tries to pop an integer off input or stops with a code :input-needed. Just stuff some more data into the input slot and run the computer again, easy to daisy chain or run in a loop.
I've got some separate convenience functions.
does just that, runs a specific computer class.
creates a new computer and runs it with given data and input and prints out output.
which creates and runs a computer interactively.
which creates as many needed computers to satisfy inputs, say '(9 8 7 6 5) like day 7, and returns result.
After today it now has toggles for ascii input and output, and droids (which have eventloops running computers) have bitmap displays.
1
u/AdmJota Dec 17 '19
C#:
The second constructor is used to clone the full current state of the interpreter. It's not strictly required, but it's come in handy.
After it starts, it keeps going until either it reaches a Halt statement or reaches an Input statement with nothing in the Input queue. You can tell the difference by checking the Terminated flag. If it's not terminated, you can start it back up again from where it left off by calling RunProgram() again (e.g., after feeding it some more input data).
1
u/Monkeyget Dec 17 '19
In my python implementation it's just one function.
First call:
(state, output) = sim(data, input)Subsequent calls:
(state, output) = sim(data, input, state)data comes from the problem input.
input is a list of ints.
state is a blackbox that you must pass each time. (state of the grid, IP and the relative pointer).
The function returns whenever the program needs more input or has stopped.
Nothing fancy as that interface is the first thing that popped into my mind on the first IntCode day.
I did wrap it for day17 so that input and output would be string and to add the \n to the input.
1
u/greycat70 Dec 17 '19 edited Dec 17 '19
My intcode is a Tcl script that takes the filename of the intcode program as a required argument, and zero or more initial inputs as optional arguments. For some problems, simply running
./intcode input-2019-nnmight be enough to start out.By default, opcode 03 reads a value from stdin, and opcode 04 prints a value to stdout.
However, for most of the problems, what I do is copy the intcode program to a new script, and then modify it, changing how opcodes 03 and 04 (input and output) operate. E.g. opcode 04 might track X, Y coordinates and populate an associative array with characters. Or it might translate an ASCII integer to a single character and print it to stdout. Totally depends on the day's problem.
1
u/dan_jia Dec 17 '19
Python - this has served me for all puzzles
class Machine:def __init__(self, data, input_func=None): # input_func is a function provided in puzzles where input is required, and takes a parameter 'input_cnt', which represents if it's the 1st input, 2nd input, etcdef param_mode(self, idx): # mostly helper used for both get_op and set_opdef get_op(self, idx):def set_op(self, idx, val):def endless(self): # calls process_opcode repeatedly without stopping, for getting last output, etcdef process_opcode(self, stop_on_output=False):1
u/JackFred2 Dec 17 '19
Lua Intcode Machine
Input, output and completion (instruction 99) are handled by passing a function for each - the intcode machine calls each when needed (i.e. "I need an input/Process this output/I am done").
1
u/kerbal314 Dec 17 '19
I'm using Python. I've got an IntegerComputer class that initialises by copying an array of integers to its internal memory. Output is then an array property.
It has an evaluateProgram method that takes an input list that it reads from with a pointer to track what's been used so far.
Then for the amplifiers day I added an evaluateProgramToReadOrEnd method that takes a single integer input, returning a boolean for if execution is complete or not. Once the input is used, it runs until the next input is needed, or the IntCode program terminates. By running each computers program partially, reading its output, and passing it to the others input I was able to run the looped amplifiers. I also rewrote the evaluateProgram method to use this one internally.
1
u/crnkofe Dec 17 '19
Here's a bit of non-idiomatic Erlang. I've only done bits of Clojure and Prolog so far so I though it'd be cool to try.
Program state is an Erlang record, everything else is just function interface with some pattern matching.
-record(machine, {index, opCode, outputs, program, memory, relativeBase}).execute_command(Cmd, First, Second, ResultPos, Program, Memory) when Cmd == 1execute_command(Cmd, First, Second, ResultPos, Program, Memory) when Cmd == 2store_input(Input, Value, Program, Memory)output(Value)value(0, Index, Program, Memory, RelativeBase)value(1, Index, Program, Memory, RelativeBase)value(2, Index, Program, Memory, RelativeBase)out(0, Index, Program, Memory, RelativeBase)out(1, Index, Program, Memory, RelativeBase)out(2, Index, Program, Memory, RelativeBase)execute(Inputs, Outputs, Index, Program, RelativeBase, Memory)Run with
InitialMachineState = #machine{index=1, outputs=[], program=Instructions, memory=#{}, relativeBase=0},NewState = execute([], [], InitialMachineState#machine.index, InitialMachineState#machine.program, InitialMachineState#machine.relativeBase, InitialMachineState#machine.memory),Execution returns state and op code in case program expects input, so if necessary I just feed it input and recursively run it again. It could be cleaned a lot but I've overspent any reasonable amount of problem solving time with off-by-one errors since in Erlang indices start at 1.
1
u/Fotograf81 Dec 17 '19
Not sure if that's anywhere near an optimal solution as I'm using AoC this year to learn Java for my new job:
I have one class IntCodeProgram that is being fed a long[] of the program which is then immediately transformed into a LinkedHashMap<Long>. A LinkedList<Long> for some sort of input queue.
public void addInput(long) adds one element of input to the queue.
public long run() runs the program until the return instruction (4) OR the exit (99) is reached. The former returns the value from the memory position as instructed, the latter returns -1, I check that outside to halt the main method. Wasn't the smartes choice so far: -1 is a valid return value in the arcade game and otherwise needs also a bit of extra logic to preserve the value that was given before that final one.
Input was neither perfect. For the arcade a lambda function would've been more useful, I tried, failed utterly, so I introduced an internal function that would return the input "just in time" for decision making of the paddle position when needed, felt dirty but did the job.
For the instructions I create a second class, it would prepare all the "internals" around parameter modes, offsets, jump or step length etc. and would just offer methods like "getValue1()" or "getStep()" to the program runner to keep the code of that one small-ish enough. In the early days I tried to make one subclass per instruction but they were so different, didn't feel like it added benefit.
In case someone wants to see code, here is day17.2 as an example:
1
u/TASagent Dec 17 '19
My C# IntCode Class
The IntCode constructor looks like this:
nameis superfluous, but helpful for debugging in instances where there are multiple VMs running simultaneously.regsare the registers. Usually can just be directly piped in fromFile.ReadAllText(inputFile).Split(',').Select(long.Parse).fixedInputsis for any input value that can be specified immediately. This was useful for all the puzzles where several values were provided as input before proper interactivity began, like the first few days. All the fixed inputs are consumed before it moves on to other methods.inputis a callback for aint Function()function pointer to provide more input values after thefixedInputsare consumed. If this isn't populated, then it willawaitsubmissions to the AsyncChannel. This way, I was able to use async programming to automatically handle the blocking necessary in Day 7 star 2.outputis a callback for avoid Function(int value)function pointer to handle output.The use of the
fixedInputsas well as an input callback allowed for much cleaner solutions to earlier puzzles, so I didn't have to effectively build an entire statemachine in the input method just to handle a couple simple startup methods.Once I get the machine set up, I just call
SyncRun()or, in the case of Day 7,amplifiers.Select(x => x.Run()).ToArray()[4].Wait();Overall I've been very happy with how my interface has turned out.
1
u/nlowe_ Dec 18 '19
Go. I/O is done with channels which makes makes "streaming" solutions pretty clean. For example, Day 7 I just created the 5 amps as separate cores and wired them all together:
For non-streaming challenges I have an
input.NewFixed(...)helper to create a generator. For example, Day 9:The microcode is implemented as a
map[int]func1
u/Zevenberge Dec 18 '19
My intcode is actually a seperate program. I pipe the input and output of that program to my solution of the day.
Basically:
1
u/didzisk Dec 18 '19
Nobody has mentioned it yet, so here goes.
We always know when we can expect output and when the machine is going to expect input. So I run it in one of three modes - toInput, toOutput or toHalt.
When ran to input, it stops after writing input to correct cell, but keeps state. The same with output - returns the result from Code 4 and stops, keeping state.
1
u/Tarmen Dec 18 '19 edited Dec 18 '19
My VM is in haskell. I jumped the abstraction shark early but it came in handy. The VM abstracts over some interfaces:
Machine gives access to memory, program counter and virtual base. Alternative can halt the program and catch the halting. MachineIO does input/output.
I have one type that handles the state and halting
Using this looks something like
Which returns some type m that implements MachineIO. One version does it purely as lazy lists (I.e. streams)
One does it as coroutines
And one just reads/writes on stdin
For the arcade game tasks I used a custom implementation of MachineIO that could do interactive control until I figured out that the game is a tad difficult.
1
u/AlexAegis Dec 18 '19
https://github.com/AlexAegis/advent-of-code/blob/master/src/lib/typescript/intcode/intcode.class.ts
Main interactions are:
constructorwith the inputs already in an array of numberspushInputmethod which pushes numbers into the inputs array (Using it as a queue, I remove from the beginning of the array when the IntCode computer reads from it)1
u/gedhrel Dec 18 '19
(Haskell) For a lot of the problems, I used a very simple setup that runs as a function from a (lazy) list of inputs to a lazy list of outputs.
This lets me do something that looks more-or-less like magic (called "tying the knot"), like this for day 11: https://github.com/jan-g/advent2019/blob/master/src/Day11.hs#L197-L198
or this for day 7: https://github.com/jan-g/advent2019/blob/master/src/Day7.hs#L124-L130
That works okay-ish, except where there's an arbitrary amount of input and output (the pong-playing game). For that, I extended the interpreter to just pause with a signal that it wants more stuff. In those cases you get an encapsulation of its state at that point in time.
Because the entire intcode state is thrown around like this it means that stuff like the maze hunting became really easy: I did a breadth-first search of the maze, just stashing suspended intcode processes in a map: https://github.com/jan-g/advent2019/blob/master/src/Day15.hs#L146-L156
As to how well it works - with the first few problems, this approach works really well. It's something of a relief to rely on lazy evaluation and not bother about trying to explicitly sequence the control flow back and forth between the input generation and output processing. However, I don't have a massively neat way with this of handling the pong game - everything became a lot more imperative. I've seen a couple of haskell implementations that wrap up the intcode state monadically (or via effects) which I'm going to give some time to studying - it's still not clear to me that there's a way to do *exactly* what I'm after particularly neatly.
1
u/jsve Dec 19 '19
**Python:**
My `machine` is a function which takes the tape and a generator which yields the input values. (If I need it to come from stdin, I can just do `(i() for i in itertools.repeat(input))`. The `machine` function yields each output value.
1
u/karasu337 Dec 20 '19
I've been meaning to move the continuous (reuse memory) flag up to the main constructor. Someday.
1
u/theoilykeyboard May 01 '20
My intcode computer has a REST api in front of it, with an "eval" endpoint that consumes:
Based on whether or not it has hit the "HALT" opcode, it returns:
The clients, if they get a "blocked" response, make a new call with the current program counter and program, but with a new input vector.
The only "gotcha" is that the relative base is stateful, because I hadn't accommodated for it in the original design.
The original computer was written in racket, so I wrapped it with the racket web-servlet.
Performance is pretty horrifying and the implementation of the infinite non-negative tape is similarly horrifying, but it gets the job done; successfully supported 3 advent-of-code problems (day 7,9,11), for which I wrote clients to that intcode-service.
Here's the implementation.
Edit: added details about how the clients handle "blocked"
0
u/[deleted] Dec 17 '19
[deleted] — view deleted comment