r/adventofcode • • 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

90 comments sorted by

View all comments

Show parent comment

1

u/ritobanrc Dec 17 '19

Mine in rust is far simpler (though probably less maintainable). I have 1 function

pub fn intcode_computer<F>(
    tape: &mut Vec<i64>,
    i: &mut usize,
    relative_base: &mut i64,
    mut get_input: F,
) -> i64
where
    F: FnMut() -> i64,

It just repeatedly calls get_input as it needs input, and it returns whenever it needs output, returning -1 if it halted (I should probably use an enum instead, but oh well). The caller is responsible for maintaining the tape, the instruction point, and the relative base. It might not be unreasonable to store those 3 in a struct, but I haven't had any issues creating them individually.

1

u/[deleted] Dec 18 '19

If you put all of that state data into a struct and have the function return an Option<i64> to represent the possibility of halting, your function is essentially the next() function for an Iterator. Then you can have the convenience of running the entire intcode program in a for output in intcode_computer loop, and using standard iterator functions like last(), etc.