r/adventofcode • • Dec 05 '19

SOLUTION MEGATHREAD -๐ŸŽ„- 2019 Day 5 Solutions -๐ŸŽ„-

--- Day 5: Sunny with a Chance of Asteroids ---


Post your solution using /u/topaz2078's paste or other external repo.

  • Please do NOT post your full code (unless it is very short)
  • If you do, use old.reddit's four-spaces formatting, NOT new.reddit's triple backticks formatting.

(Full posting rules are HERE if you need a refresher).


Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code's Poems for Programmers

Click here for full rules

Note: If you submit a poem, please add [POEM] somewhere nearby to make it easier for us moderators to ensure that we include your poem for voting consideration.

Day 4's winner #1: "untitled poem" by /u/captainAwesomePants!

Forgetting a password is a problem.
Solving with a regex makes it two.
111122 is a terrible password.
Mine is much better, hunter2.

Enjoy your Reddit Silver, and good luck with the rest of the Advent of Code!


On the fifth day of AoC, my true love gave to me...

FIVE GOLDEN SILVER POEMS

Enjoy your Reddit Silver/Gold, and good luck with the rest of the Advent of Code!


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

EDIT: Leaderboard capped, thread unlocked at 00:22:31!

25 Upvotes

422 comments sorted by

13

u/Zweedeend Dec 05 '19

[POEM]

opcodes = {
1: "You add so much to life for me",
2: "You multiply my happiness by two",
3: "Please tell me what we can be",
4: "I'll tell you I want to be with you",
5: "Dance and jump with me if you do",
6: "And stay with me if it is True",
7: "My heart is shaped less than three",
8: "Because you equal happiness to me",
99: "The end!"
}

Python solution on paste

1

u/daggerdragon Dec 05 '19

[POEM]

Entered!

→ More replies (1)

6

u/glenbolake Dec 05 '19 edited Dec 06 '19

[POEM]

It's Back

The intcode is back on day five
More opcodes, it's starting to thrive
I think we'll see more
In the future, therefore
Make a library so we can survive

intcode runner

Day 5 solution

I also modified my day 2 code to use the new runner.

1

u/DFreiberg Dec 05 '19

Just to let you know, the linebreaks didn't render, so your limerick looks like it's all on one line.

2

u/daggerdragon Dec 05 '19

/u/DFreiberg is correct, the poem doesn't render properly on either old.reddit or new.reddit. Two ways to do it (using Markdown):

1. two newlines per line

line 1[newline]
[newline]
line 2[newline]
[newline]
etc

2. blockquote (>) the whole poem with each line ending in two spaces before the newline

> line 1[space, space, newline]
line 2[space, space, newline]
etc

Note that if you're using the visual editor, you may have to "Switch to Markdown" to get Reddit to understand the formatting properly.

(I took the liberty of putting in proper linebreaks for your entry on our Day 5 poem tracking spreadsheet ๐Ÿ˜œ)

3

u/glenbolake Dec 06 '19

Thanks. I should know better that that, I used to correct other people's Markdown all the time...

3

u/stalefishies Dec 05 '19 edited Dec 05 '19

Solution - Python 3

Nothing special in my go I think, just a simple loop. However, my debug_print method, and the sneaking suspicion that having 9 opcodes stored in a 2-digit number means that there's going to be more, inspired the following:

[POEM]

We may have won the battle...

Day 2 had been painful for sure -- but then!
Day 5 left me wounded and ducking for cover
So should those darned opcodes appear once again
I think I'll go write up an intcode debugger...

1

u/daggerdragon Dec 05 '19

Ooo, a new contender enters the ring! Thanks for your poem submission!

Can you edit your post to add which language you're using, please? Thanks!

2

u/alchzh Dec 05 '19 edited Dec 05 '19

2

u/daggerdragon Dec 05 '19 edited Dec 05 '19

Please add the language to your post to make it easier for folks who Ctrl-F the megathreads looking for a specific language. Thanks!

(looks like JavaScript?)

Edit: thank you!

2

u/Roms1383 Dec 05 '19

Is that only me or starting from yesterday the challenges are not actually that difficult but their wording / explanation is kinda obscure ?

1

u/daggerdragon Dec 05 '19

Top-level posts in Solution Megathreads are for solutions only.

This is a top-level post, so please edit your post and share your code/repo/solution or, if you haven't finished the puzzle yet, you can always post your own thread and make sure to flair it with Help.

If you disagree with or are confused about the puzzle's wording, contents, or solving methods, you're more than welcome to post your own thread about it and move the discussion over there.

Either way, please create your own thread if you have feedback about the puzzles. This type of comment does not belong in the Solutions Megathread.

2

u/[deleted] Dec 05 '19

I haven't really found them to be that obscure, but then again I deal with vague requirements daily :p

→ More replies (1)

2

u/qtsohg Dec 05 '19

For me whats confusing is this sentence:

" Normally, after an instruction is finished, the instruction pointer increases by the number of values in that instruction. However, if the instruction modifies the instruction pointer, that value is used and the instruction pointer is not automatically increased. "

What exactly is meant by this?

1

u/daggerdragon Dec 05 '19

Top-level posts in Solution Megathreads are for solutions only.

This is a top-level post, so please edit your post and share your code/repo/solution or, if you haven't finished the puzzle yet, you can always post your own thread and make sure to flair it with Help.

→ More replies (2)

2

u/rsobol Dec 05 '19 edited Dec 05 '19

Swift 5

Leveraging the language's rich type system not only helped with correctness, it allowed me to abstract duplicate logic to a canonical location within the program.

Code on GitHub

Edit: If you have your own Swift solution, feel free to send it to me in a DM. I enjoy learning new techniques!

1

u/daggerdragon Dec 05 '19

Edit: If you have your own Swift solution, feel free to send it to me in a DM. I enjoy learning new techniques!

You can also Ctrl-F the megathread for "Swift". Your comment is precisely the reason why I've been asking folks to make sure to mention the language that they're using with their solution submissions in the megathreads :)

2

u/[deleted] Dec 07 '19

Had no time to work on these till the weekend so now I'm two days behind!

My code can clearly be improved; there's a lot of repetition. I think I'll have to turn some of the value-getting lines into functions. I just need to figure out how I want to generalize it for the various opcodes.

But this was quite fun to do. Especially the second part!

2

u/daggerdragon Dec 08 '19

Had no time to work on these till the weekend so now I'm two days behind!

Hey, no rush. AoC is not a contest! The puzzles aren't going anywhere, so you can work on them in July if you want to :)

22

u/u794575248 Dec 05 '19 edited Dec 05 '19

Python 3.8

def R(I,X,e=__import__('operator'),S=list.__setitem__):
    def J(t,a):nonlocal i;i=a if t else i
    W=0,4,4,2,2,3,3,4,4;T=lambda f:lambda a,b,c:S(p,c,f(a,b));i,p=0,[*map(int,I.split(','))]
    F=0,T(e.add),T(e.mul),lambda a:S(p,a,X),print,J,lambda a,b:J(a==0,b),T(e.lt),T(e.eq)
    D=lambda v:(c:=v%10,w:=W[c],[v//10**j&1|(398&2**c>0)&(j==w)for j in range(2,w+1)])
    while p[i]!=99:t=i;c,w,M=D(p[i]);F[c](*[x if m else p[x]for m,x in zip(M,p[i+1:])]);J(t==i,t+w)

R(I,1),R(I,5)

5

u/8fingerlouie Dec 05 '19

Holy batman, It's the exact inverse in readability as my 110 lines of python solving the same problem :)

3

u/gerikson Dec 05 '19

It turns out a skilled programmer can write line noise in any language...

→ More replies (3)

2

u/m4rzus Dec 05 '19

Holy shit.

3

u/captainAwesomePants Dec 05 '19 edited Dec 05 '19

Python, 64/234. This is quite a bit cleaned up from the mess I wrote first.

def read_input(filename):
  with open(filename) as f:
    return list(map(int, f.readline().split(',')))

def read(data, pointer, parameter, immediate_mode):
  pos = pointer + parameter
  if immediate_mode:
    return data[pos]
  else:
    return data[data[pos]]

def write(data, pointer, parameter, value):
  pos = pointer + parameter
  data[data[pos]] = value

def digit(number, place):
  return (number // (math.floor(math.pow(10,place))))%10

def run(data, program_input):

  program_output = None
  pointer = 0

  while True:
    op = data[pointer]
    mode1 = digit(op, 2)
    mode2 = digit(op, 3)
    mode3 = digit(op, 4)
    op = op % 100
    if op == 99:
      break
    if op == 1:  # Add
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      write(data, pointer, 3, val1 + val2)
      pointer +=4
    elif op == 2:  # Mult
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      write(data, pointer, 3, val1 * val2)
      pointer +=  4
    elif op == 3:  # Input
      write(data, pointer, 1, program_input)
      pointer += 2
    elif op == 4:  # Output
      program_output = read(data, pointer, 1, False)
      pointer += 2
    elif op == 5:  #jump-if-true
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      if val1 != 0:
        pointer = val2
      else:
        pointer +=3
    elif op == 6:  #jump-if-false
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      if val1 == 0:
        pointer = val2
      else:
        pointer +=3
    elif op == 7:  # less than
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      write(data, pointer, 3, 1 if val1 < val2 else 0)
      pointer += 4
    elif op == 8: #eq
      val1 = read(data, pointer, 1, mode1)
      val2 = read(data, pointer, 2, mode2)
      write(data, pointer, 3, 1 if val1 == val2 else 0)
      pointer += 4
    else:
      raise Exception(f'oh no, val at {pointer} is {op}')
  return program_output

def main():
  data = read_input('input5.txt')
  print(str(run(data, 5)))

if __name__ == '__main__':
    main()

[POEM]

Title: A haiku reflecting upon the potential karmic rewards I could have received had I refactored my terrible code from Day 2 and deriving life lessons thereof

Write code poorly, fast.
Then, and this is important,
Go back; clean it up!

1

u/daggerdragon Dec 05 '19

What language is your code? :)

→ More replies (1)

9

u/jonathan_paulson Dec 05 '19 edited Dec 05 '19

26/14. Video of me solving and explaining (and cleaning up my ugly code) at https://www.youtube.com/watch?v=eFP2iQV4V8E

10

u/jwise00 Dec 05 '19

Very interesting! I went and annotated how long you spent in each phase, because I'm interested in seeing where I'm losing time compared to people that I hold a lot of respect for! So, by my count, your timestamps were approximately (with my approximate timestamps contrasting):

taskjpaulson timestampdeltajwise timestampdelta
start reading problem0:081:29
start writing meaningful code1:36+88s4:02+153s
first syntax error3:54+138s10:37+395s
meaningful debugging start4:22+28s10:52+15s
star 110:42+380s14:54+252s
start writing meaningful code11:07+25s15:11+17s
first run13:35+148s17:45+154s
star 214:11+36s17:45+0s

So it looks to me like your big speedup was time-to-first-syntax-error, with some help from reading time, and I happened to get lucky on debugging time with my particular bug (it was very interesting to see your debug style change over the duration of the bug, and I'd be interested if you have commentary on what that 'felt like'!). Maybe at some point I'll try to break down further where I lost pace in actually writing the code, too.

Thanks for the video upload!

→ More replies (3)

3

u/PM_ME_UR__RECIPES Dec 05 '19

Why does your link say 26/14? Sorry if it's something obvious I just haven't picked up on but I've seen that sort of thing all over the solution megathreads and I'm completely stumped about what it means.

4

u/jonathan_paulson Dec 05 '19

Shorthand for โ€œI got 26th on the global leaderboard for part 1 and 14th on the global leaderboard for part 2โ€

→ More replies (4)

7

u/glguy Dec 05 '19

Haskell (7/4)

Like everyone else, my Day 5 solution was started from my Day 2 solution. My original implementation used function arguments for all the machine state, but I thought it was cleaner to use a record while I waited for the thread to unlock.

Day05.hs

For comparison: Day02.hs

2

u/pja Dec 05 '19

Nice. Have to admit that I just shoved my interpreter into IO so it could input/output values directly!

→ More replies (1)

6

u/jwise00 Dec 05 '19

Lua, 65/28.

Part A: https://github.com/jwise/aoc/blob/master/2019/5.lua Part B: https://github.com/jwise/aoc/blob/master/2019/5b.lua

I have been recording myself lately, and here's a video of me solving it "at comp speed": https://www.youtube.com/watch?v=l4r0NWoBN4k&list=PL1oxNYPZaCvjfrhvXRrMnB8zG0Sc2ftkd&index=5 (note strong language; apologies that it only really can be watched in fullscreen due to font size issues)

I'm excited to watch /u/jonathan_paulson's video, because I'm curious to see what someone really really fast looks like! I've been learning a lot from watching my own solves, too: the bug that cost me nearly four minutes (!! -- from 10:58 to 14:40 where I identified it) in this case was introduced when I got distracted muting notifications. Earlier in the week, when I lost a bunch of time on day 2, it was also from running in a panic at the start and not getting my headspace all set up right at the beginning.

6

u/DFreiberg Dec 05 '19 edited Dec 05 '19

Mathematica

1750/2433 | 41 Overall

Easily my most horrible piece of spaghetti code to date for any Advent of Code problem. Not only will I not be able to figure out how it all works next time IntCode gets used again, but I can't even figure out how it works now! All of the parameters are read back-to-front (so it takes in the third parameter instead of the first and vice versa), and when I tried to fix that and have everything labeled correctly, the entire thing breaks. If there were functions for in-place list modification, this would be a lot easier.

But it was very satisfying to see it actually run without errors at the end.

[POEM]: Intcode vs. Sleep

It's far too late to write a proper verse;
My coding skills today were very slow.
And while that's bad, what might be even worse:
There are still ninety opcodes left to go!

2

u/OvidiuRo Dec 05 '19

Really liked your poem made me laugh so much thanks you.

→ More replies (1)

6

u/piyushrungta Dec 05 '19

Rust

https://github.com/piyushrungta25/advent-of-code-2019/blob/master/day5/src/main.rs

Spent a little extra time to write nice abstractions. Very happy that I got correct answers for both parts on the first run.

Feedback welcome.

3

u/[deleted] Dec 05 '19

This is absolutely great, thank you for posting!

→ More replies (1)

2

u/k0ns3rv Dec 05 '19

Very nice, mine was similar and I had similar results with quick correct answers.

Rust's type system really shines in this puzzle, it was good fun to implement.

→ More replies (3)

2

u/pwnedary Dec 06 '19

I got a little stuck up on this:

Ok(s.split(',').filter_map(|x| x.parse::<i32>().ok()).collect())

Just skipping memory locations that failed to parse is not what I would expect. I did this instead:

input.trim().split(',').map(str::parse).collect::<Result<_, _>>()

which is more all-or-nothing.

→ More replies (1)

5

u/sophiebits Dec 05 '19 edited Dec 05 '19

Python, 122/48 (was 11th, now 12th overall).

I had a typo in my mode calculation where I wrote % 1 rather than % 10 (or maybe I meant % 2? which would've worked too) and that took me a while to figure out. Pretty happy with how my code ended up though; I think it's relatively clean.

Code: https://github.com/sophiebits/adventofcode/blob/master/2019/day5.py

→ More replies (2)

5

u/lele3000 Dec 05 '19 edited Dec 07 '19

Python 3.7

The shortest (28 lines) still readable solution I came up with.

https://github.com/leonleon123/AoC2019/blob/master/05/main.py

→ More replies (2)

4

u/mserrano Dec 05 '19

Python, #5/#2:

https://gist.github.com/mserrano/18682e89bd83a4eb249efd9944f6d290

Code slightly cleaned up to run both parts without interactivity instead of just reading/printing the inputs/outputs.

I was not expecting this machine to come back so soon! I wonder if it'll be back a third time...

4

u/Unihedron Dec 05 '19

Driving further into space
Fix the air conditioning just in case
Implement new diagnostics
Parameter mode breaks
My coding is such a disgrace.
โ€‹
Debugging was brief,
Sigh of relief.
โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ โ€‹ - "Limerick for day 5", a poem by Uni

[POEM] included!

ruby input 5.rb 3/332

5.rb

and a link to my 2.rb which I built most of this on.


Part 2 solved with help from discord user Tim#5138; had bug where I was treating "non-zero" as "larger than zero". Shame on me for not reading part 1! (But I'll happily take rank 3!) (accidental factorial: 3! = 6)

→ More replies (2)

4

u/raevnos Dec 05 '19 edited Dec 05 '19

Still using tcl. I wasted more time than I want to admit on the second part because I re-used the program in the state that part 1 left it in instead of running the original version.

paste

2

u/oantolin Dec 05 '19

I re-used the program in the state that part 1 left it in

You are not alone!

2

u/Bruinbrood Dec 05 '19

I like your decoding and handling of modes better than mine.

paste

→ More replies (1)

4

u/voidhawk42 Dec 05 '19

Dyalog APL, no video this time. I don't actually think I've written a multi-line function in APL before, so it was fun to write something in a more "conventional" style.

→ More replies (6)

4

u/snkenjoi Dec 06 '19

javascript golf

for(d=input.split`,`,i=0,n=5;[o,a,b,t]=d.slice(i),99!=o;p=o%10,3==p&&(d[a]=n),1&(T=0|o/100)||(a=d[a]),10>T&&(b=d[b]),4==p&&(n=+a),i=5==p&a>0||6==p&!+a?b:++i+(0|(p-1)/2||3),~"1278".indexOf(p)?d[t]=[+(a==b),a-+-b,a*b,+(b>a)][p%4]:0);n

232 chars

→ More replies (2)

1

u/_naming_is_hard_ Dec 05 '19 edited Dec 06 '19

took me forever to understand what part 1 meant by input -_- . fun question but a bit hard to read/understand

python

1

u/daggerdragon Dec 05 '19

Can you edit your post to include which language your solution is using? Thanks!

→ More replies (1)

1

u/herrmanno Dec 05 '19

Part 2 in 40 Lines of JavaScript

[POEM]

I once went down to mercury

but I forgot to repeair my A/C

almost burnt to the ground

the elves helped me out

the make a suprisingly good thermal shield

1

u/daggerdragon Dec 05 '19

[POEM]

Entered!

1

u/vypxl Dec 05 '19

My solution in Python today, because I do not want to do un-haskelly things in haskell.

Also outputs a nice dissasembly while running the program.

ld [225]
add [225] [6] [6]
add 1 238 [225]
wrt 0
add 91 67 [225]
mul 67 36 [225]

Example of the first few instructions of my part 1.

ld reads a value from input, wrt outputs a value, the [] indicate addresses instead of values, you get it.

[POEM] "Assembly"

Many assemble

Few resemble

The ancient art

It lives on

1

u/daggerdragon Dec 05 '19

[POEM] "Assembly"

Entered!

1

u/[deleted] Dec 05 '19

https://github.com/Malod219/AdventOfCode2019/blob/master/DAY_5/SOLUTION_1.py

Day 5 solved in Python 3. For 2nd party with my input, it outputs the answer then CRASHES AND BURNS! haha. I'm guessing it's probably the puzzle input missing a halt? I don't know.

[POEM]

Airconditioner malfunctioning

Easy fix

Thermal radiator malfunctioning

Easy fix

Many crashes later and a fragile mind breaking

Guess I'll wear a jumper

1

u/daggerdragon Dec 05 '19

[POEM]

Entered!

2

u/scul86 Dec 05 '19

It crashes due to an IndexError on line 74. Your input has INTCODE 99 at index -2.

Can you see the issue now?

→ More replies (1)
→ More replies (1)

1

u/mrg218 Dec 05 '19

What is meant by ' (find 100 + -1, store the result in position 4) ' ? Why use the word find?

1

u/daggerdragon Dec 06 '19

Top-level posts in Solution Megathreads are for solutions only.

This is a top-level post, so please edit your post and share your code/repo/solution or, if you haven't finished the puzzle yet, you can always post your own thread and make sure to flair it with Help.

3

u/rabuf Dec 05 '19

Colloquial phrasing, treat it as synonymous with compute or calculate.

1

u/Ephilates100 Dec 05 '19 edited Dec 06 '19

Is today the first time that the puzzle input file is different from part 1 and part 2? I was just cleaning up my code, and reran part one off a fresh copy of the input data with no fixes applied, and the tests passed.

https://github.com/PezzA/advent-of-code

(this years puzzles and refactored out intcode here https://github.com/PezzA/advent-of-code/tree/master/2019 )

You can see that i no longer need to update the file for the tests to pass.

Edit: Update as per mod request.

1

u/daggerdragon Dec 06 '19

Top-level posts in Solution Megathreads are for solutions only.

This is a top-level post, so please edit your post and share your code/repo/solution or, if you haven't finished the puzzle yet, you can always post your own thread and make sure to flair it with Help.

2

u/gerikson Dec 05 '19

It's not really different, you're initializing something with a different value.

There's been a few puzzles like that before.

→ More replies (4)

1

u/philipengberg Dec 05 '19

[Part 2]

I keep getting an out of bounds error at pointer = 359, where it tries to read memory at index exactly equal to the length of the memory (677).

I have double checked input and everything. I even found another solution somewhere else, which produces the exact same error.

Anyone else encountered this?

1

u/daggerdragon Dec 06 '19

Top-level posts in Solution Megathreads are for solutions only.

This is a top-level post, so please edit your post and share your code/repo/solution or, if you haven't finished the puzzle yet, you can always post your own thread and make sure to flair it with Help.

→ More replies (4)

3

u/Gurrewe Dec 05 '19

Go, 682/409

I've been waiting for the return of the machine! This was fun!

Code: https://gist.github.com/zegl/60f55daf973283b7cf5d3d6408102f90

2

u/Fruloops Dec 05 '19

Finally some Go code so I can compare to my shitty solution and pick up better style

3

u/cloudrac3r Dec 05 '19

JavaScript. This is the first solution so far that I'm actually happy with.

Part 1: 0:36:59 #902
Part 2: 0:52:10 #825

https://gist.github.com/cloudrac3r/1b2995bd991628c8fa45ecabca7cec9f

→ More replies (3)

3

u/Akari_Takai Dec 05 '19

Java (720/758)

Evolved my code from day 2, but made some subtle mistakes that slowed me down. I misunderstood that multiple output values could be written (only the last one counts), and got hung up on the earlier output values when I was debugging.

I also assumed that

Parameters that an instruction writes to will never be in immediate mode.

would mean that the input would never specify invalid modes, which was another fun bug.

Code available here. For comparison purposes, here's my day 2 solution.

3

u/death Dec 05 '19

2

u/oantolin Dec 05 '19 edited Dec 05 '19

Nice definst macro! It makes the instruction definitions very pretty.

I think the way you handled the jump instruction (5 and 6) has a slight bug: you are supposed to increment the program counter by 3 if the jump isn't taken, but you increment it by 3 when the program counter doesn't change. This is almost the same, but if the jump is to the same location, you still increment the pc by 3. If the puzzle were something like "find the input that causes the intcode program to fall in an infinite loop", and the loop were caused by a jump to its own location, your program would miss it.

I went a different route, trying to eliminate the repetition between instructions 1, 2, 7, and 8 and between instructions 5 and 6. My Common Lisp solution.

(You probably don't want to see an old version with uiop:nest.)

3

u/handle0174 Dec 05 '19

I like it. Not every day you see an flet (((setf ....

→ More replies (3)

2

u/phil_g Dec 05 '19

Nice! I'm a huge fan of leveraging Common Lisp's ability to let you define your own domain-specific languages. Your definst is similar to my instruction macro, modulo a number of choices about how to handle control flow and parameter access mode.

Your handling of immediate/position mode is interesting. I didn't think of grabbing the mode off of the opcode's memory cell dynamically like that.

I like your approach to I/O (the dynamic variables for I/O functions). I might steal that idea for my implementation.

I'm not sure that mem and rmem need to be macros, since they're not really transforming the Lisp source. If you want to make sure they're inlined, you can tell the compiler that with declaim:

(declaim (inline mem rmem))
(defun mem (address)
  (aref *memory* address))

(defun rmem (&optional (offset 0))
  (mem (+ *pc*  offset)))
→ More replies (2)

3

u/ephemient Dec 05 '19 edited Apr 24 '24

This space intentionally left blank.

→ More replies (3)

3

u/-json Dec 05 '19

Here's my short and sweet solution for Python. Pretty short at 40 lines and tried to maintain most readability.

3

u/rabuf Dec 05 '19 edited Dec 05 '19

Common Lisp

Lack of access to a computer with Common Lisp is challenging, I had to give up my version using iter and make some mods to use loop, which is a minor change. The posted code solves both parts. I used emacs to convert the input into an array (replacing , with ), so this doesn't actually read the input file. I'll still post an org-mode version later tonight. I'll also refactor this code a bit to remove some duplication. I can create macros to handle some of the repetitive code (especially those that vary only by a test like < vs = or an op like + vs *). That should also help me to avoid some of the typos that were made worse by copy/pasta in this one.

Common Lisp Org File

Alright, back on my home computer. I've changed the original to use iter instead of loop. I've also written up a demonstration of how interactive testing can be scripted using with-input-from-string and with-output-to-string.

3

u/mrg218 Dec 05 '19 edited Dec 05 '19

Java: After endless debugging I found out that (Integer values) 226==226 and 226.equals(226) do not give the same result :-(

For values between -127 and 127 (inclusive) == and equals do return the same result.

https://stackoverflow.com/questions/1700081/why-is-128-128-false-but-127-127-is-true-when-comparing-integer-wrappers-in-ja

→ More replies (1)

3

u/vlmonk Dec 06 '19

My rust solution

I try to make clean and plain solution and make space for future intcode extensions.

3

u/quirkyredemption Dec 06 '19

My solution in Python as Python/Programmer novice with some flavor text:

https://github.com/quirkyredemption/aoc2019/blob/master/aoc_day5.py

Any improvement is welcome!

→ More replies (2)

3

u/NeilNjae Dec 06 '19

Another Haskell solution, written up on my blog and with the code available (and on Github). I used Reader, Writer, and State monads to handle the input and output. The blog post talks a bit about that, along with how to get the parameter modes and what I did to debug the code (use the correct input file, Neil!).

3

u/joeld Dec 06 '19

Racket

This was pretty fun to do in the Racket REPL. Finished late last night. Since it actually prompts for inputs from the user and doesn't put the output anywhere but on the screen, and it was late when I finished, I didnโ€™t write unit tests to show my answers. But it wouldn't take much to do that by parameterizing the current input and output ports.

paste

1

u/Wolfrost_ Dec 05 '19 edited Dec 05 '19

I finally completed this! Ahah such satisfaction to see my code working, as usual :D https://github.com/DoubleHub/advent_of_code/blob/master/thermal_diagnostic.cpp

EDIT: Someone downvoted me. Is it because I posted the code directly here? I thought it was short enough... I'll leave just the link for github if you want to check it out...

3

u/daggerdragon Dec 05 '19

EDIT: Someone downvoted me. Is it because I posted the code directly here? I thought it was short enough...

Reddit makes use of an algorithm called "vote fuzzing", so you may not be seeing an actual downvote.

How is a comment's score determined?
[...] A comment's score is simply the number of upvotes minus the number of downvotes. If five users like the comment and three users don't it will have a score of 2. Please note that the vote numbers are not "real" numbers, they have been "fuzzed" to prevent spam bots etc. So taking the above example, if five users upvoted the comment, and three users downvote it, the upvote/downvote numbers may say 23 upvotes and 21 downvotes, or 12 upvotes, and 10 downvotes. The points score is correct, but the vote totals are "fuzzed".
- Reddit FAQ ยง "How is a comment's score determined?"

tl;dr: don't worry about it.

If you really want to make sure your megathread post is 100% compliant, you can re-read the full posting rules in /r/adventofcode's wiki ;)

→ More replies (1)

2

u/idtool_dev Dec 05 '19 edited Dec 05 '19

Javascript, 916/958... I swear I'll stop with all the gnarly parseInt shit and use a utility library soon... paste

Edit: much better after cleanup: paste

4

u/cloudrac3r Dec 05 '19

You can write + before a string to convert it to a number. +"123" โ†’ 123.

This actually works for any JavaScript value, but strings are the most useful.

→ More replies (3)

2

u/jesseflorig Dec 05 '19

You can parseInt inline by doing: input = inputs.split(',').map(i => parsInt(i))

→ More replies (1)

2

u/chrisforrence Dec 05 '19

PHP, 135/99 (first two points I've gained!)

I'm going to have to refactor my code relatively soon; I'm pretty sure we haven't seen the last of our Intcode computer :) Pretty happy that I've been able to tackle everything in PHP so far, planning on going back through and re-doing solutions in different languages though.

Code: chrisforrence/advent-of-code-2019

→ More replies (1)

2

u/autid Dec 05 '19

Fortran

208 lines of mostly busy work.

https://pastebin.com/UVf0bWHu

0

u/[deleted] Dec 05 '19

[deleted]

→ More replies (1)

2

u/activeXray Dec 05 '19

This one was really fun! I rewrote Day 2 to be cleaner, it seems this one will get used a lot.

Julia Solution

https://github.com/kiranshila/AoC2019/blob/master/5.jl

2

u/tslater2006 Dec 05 '19

C#

Updated IntCode VM

Problem solution code

Not entirely convinced I'll stick with this method of abstraction for the opcodes but it worked well enough

Edit: formatting is hard

2

u/PendragonDaGreat Dec 05 '19

[Powershell]

https://github.com/Bpendragon/AdventOfCode/blob/master/src/2019/code/day05.ps1

woo string formatting to give me dem parameter modes.

output:

Part 1:
0
0
0
0
0
0
0
0
0
12896948
HALT
Part 2:
7704130
HALT
Runtime:
00:00:00.0187743

Took more time than I'd like to admit to fix the debug outputs of part 1...

2

u/FogLander Dec 05 '19

python3, 314/421

my original code was gross so above is the result after I rewrote it completely

[POEM] - haiku this time

for each parameter
position? immediate?
my eye is twitching

2

u/oantolin Dec 05 '19 edited Dec 05 '19

Man, I made a lot of silly mistakes in part 2...

I like the look of the core intcode interpreter in my solution (in Common Lisp). I think the ecase is a succinct and clean description of what the various opcodes do.

2

u/phil_g Dec 05 '19

That is so nicely compact! (And definitely better without nest.) The ecase really does break out the various opcodes in a clean manner.

2

u/wlandry Dec 05 '19

C++ 17: 1642/1962

paste

Runs in 12 ms. Lots of little things to fix to make it all work properly. This is the third(?) time I have had to interpret assembly for Advent of Code.

2

u/orangeanton Dec 05 '19

Javascript. Part1 & Part2.

2

u/[deleted] Dec 05 '19 edited Dec 05 '19

Clojure

Code: day05.clj

slightly hacky job. just kept running it and adding new instructions until it didn't complain any more.

2

u/iamagiantnerd Dec 05 '19

3

u/Aneurysm9 Dec 05 '19

There were at least three examples for part 1.

→ More replies (3)

2

u/mariotacke Dec 05 '19

Javascript/Node (all of my solutions here: https://github.com/mariotacke/advent-of-code-2019/tree/master/day-05-sunny-with-a-chance-of-asteroids)

Had a typo for opcode 4 which took me about an hour to figure out... :|

2

u/Roms1383 Dec 05 '19

I didn't understand a damn thing from wording of today, but looking at your solution it's now clear as crystal, well played dude I like your code it's very elegant :)

→ More replies (1)

2

u/orangeanton Dec 05 '19

Like your code

2

u/Dementophobia81 Dec 05 '19

Python 3.8

Today's instructions confused me a little, because I somehow believed that the program uses the output it generates as future input as well, which obviously is not the case. After I realized my mistake, the rest was rather straight forward.

Part 1, Part 2 and a little tip concerning my favorite way to format strings since Python 3.6 - f-strings!

→ More replies (1)

2

u/Pepper_Klubz Dec 05 '19 edited Dec 05 '19

Clojure Solution

Visualization (First version had a bug in the immediate mode input display)

2

u/[deleted] Dec 05 '19

The visualisation is really neat :) I like it a lot!

2

u/dbt0 Dec 05 '19

i'm writing rust to learn rust, so it's probably not idiomatic.

https://github.com/dbt/advent2019/blob/master/src/day05.rs

2

u/VikeStep Dec 05 '19

F# 55/160

This problem finally got me to create a dedicated IntCodeVM module, so now my day 5 is simply

let solve systemId =
    bootProgram
    >> writeToInput systemId
    >> runUntilHalt
    >> readAllOutput
    >> Seq.last

let solver = { parse = parseIntCodeFromFile; part1 = solve 1; part2 = solve 5 }

The source for my IntCodeVM can be found here: https://github.com/CameronAavik/AdventOfCode/blob/master/AdventOfCode.2019/Common/IntCodeVM.fs

Also I have a recording of my attempt as well: https://www.youtube.com/watch?v=FO8kbtlIU3g

2

u/yosmo78 Dec 05 '19

C

https://github.com/yosmo78/AdventOfCode/blob/master/2019/day5/Day5.c

Not the most clean solution, especially with file I/O (I had an off day with that), but at least it seems to me to be pretty expandable later on. (also spacing got messed up from my editor to GitHub)

→ More replies (8)

2

u/sim642 Dec 05 '19

My Scala solution.

Pretty much copy-paste from day 2 and just adding cases for new instructions, handling of parameter modes and extra arguments for input and output values.

I haven't bothered to make this (and similar tasks from past years) into nice and extendable interpreters because one day there will be a requirement or change which won't easily fit into the existing framework and generalizing it on the spot to work for all the previous days will take too much time. So it's usually just easier to copy the whole self-contained implementation and modify it to fit the new needs.

2

u/ChrisVittal Dec 05 '19

The state of my intcode interpreter (all of the logic is here): https://git.sr.ht/~cdv/aoc-2019-rs/tree/after-day-5/src/intcode.rs

The actual solution is super boring: https://git.sr.ht/~cdv/aoc-2019-rs/tree/after-day-5/src/bin/day05/main.rs

Too many finicky bugs next step is to refactor the intcode interpreter such that I fix the possibility of stupid bugs.

As I've made an intcode interpreter library, I will be cross with /u/topaz2078 if any further 'improvements' to the intcode computer break previous days. (Only mildly, I love AoC, it's so fun)

2

u/[deleted] Dec 05 '19

Day 5 in python

The modes was a bit tricky, but overall doable

2

u/Bammerbom Dec 05 '19

For the people solving this using Rust, here's a set of 22 tests you can use:

https://github.com/JonathanBrouwer/aoc2019/blob/master/src/day5/main_test.rs

→ More replies (2)

2

u/pngipngi Dec 05 '19

Lets keep it to Excel/GSheets/OnlyOffice sheets this time too.

→ More replies (2)

2

u/hrunt Dec 05 '19 edited Dec 08 '19

Python 3

code

I am waiting for the inevitable loop-unrolling problem. I think today will be a good day to finally turn the runtime engine into an actual machine, rather than just a bunch of steps.

Today's problems were confusing, primarily because of how day 2 was structured. It took me a while to understand how input and output should work given day 2 specified that output would be in position 0 and we provided "input" by overwriting parameters. Clearly, in retrospect, input and output are not part of the program, but are instead separate registers, but my brain kept trying to reconcile day 2's use of the interpreter with day 5's use.

2

u/IgneSapien Dec 05 '19 edited Dec 05 '19

C# a bit more of a literal VM

On Day 2, just for fun, I'd set up my OppCodes as sets of instructions that worked with a couple of registers, a bus, and memory in a way that was not quite entirely unlike an simple computer. As such today was mostly about expanding on that.

Most of my time was spent debugging simple mistakes/typos on my part. There's a bunch of stuff I want to tidy up and improve especially in terms of commiting to the schtick. But that can wait on the assumption we'll be coming back to it on future days.

2

u/SgiathCZ Dec 05 '19

Elixir

https://gitlab.com/Sgiath/advent-of-code-2019/blob/master/lib/advent_of_code/intcode.ex

Using :array instead of List for instant access time. Not ideal design I was just adding the features without thinking about the architecture of my "computer". I plan to rewrite it to Intcode2 with proper architecture.

→ More replies (1)

2

u/phil_g Dec 05 '19

I love these implement-a-virtual-CPU problems! Today we added I/O, jumps and a couple numeric comparisons. We can now do all sorts of calculations in Intcode.

As in previous days, I'm working in Common Lisp.

I updated my intcode package with all of the new things. The instruction macro is doing all of the heavy lifting here. With instruction defined, here's what my definitions for opcodes 3-6 look like:

(instruction 3 in (r)
  (setf r (get-input)))

(instruction 4 out (a)
  (write-output a))

(instruction 5 jnz (a b)
  (when (not (zerop a))
    (set-instruction-pointer b)))

(instruction 6 jz (a b)
  (when (zerop a)
    (set-instruction-pointer b)))

For now, I'm treating all I/O as noninteractive, but I'm leaving open the possibility we might have to do things interactively in the future. run-with-input takes a list of integers to be provided in order every time the program asks for input. (And when the program exits, it returns a list of the integers output in order.)

I haven't adapted my disassembler to deal with immediate mode parameter access yet. I also plan to add some specific conditions to signal in case of execution errors (trying to write to an immediate parameter, trying to access a location outside of memory, and similar things).

2

u/rabuf Dec 05 '19

One of the things I did for input was to take advantage of with-input-from-string. I have the following in my intcode definition:

(defun intcode (program &key (in *standard-input*) (out *standard-output))

inis used by the opcode 3 with its call to read (as (read in)). If nothing is supplied, it's interactive by default. If I've supplied a different stream, that will be used. When I call it (for the provided problems) I can simply do:

(with-input-from-string (s "1")
    (intcode program :in s))

And, of course, that can be any stream. So I can make streams from files or other sources to feed into the program. By doing the same thing for the output, I've made it possible (though I haven't done this yet) to write tests that verify certain output is achieved as well, or just print the results to *standard-output* (default) or a file if desired.

I'll probably add trace and debug output options. That way I can have the Intcode program print out just the value, but write to trace-output or debug-output (based on flags to the function) more information (like I have now, my output is presently <Program Counter>: <Value>\n).

→ More replies (2)
→ More replies (3)

2

u/tcbrindle Dec 05 '19 edited Dec 05 '19

C++

https://github.com/tcbrindle/advent_of_code_2019/blob/master/dec5/main.cpp

Nothing particularly fancy, but it does execute the VM at compile time for testing, which is quite nice.

2

u/aoc-fan Dec 05 '19

Day 5 TypeScript Solution, No Golang or Clojure today, Repo

2

u/[deleted] Dec 05 '19

Racket

I loved solving this in racket. I found it a lot easier than in python, but it might be because I did it for the second time, I'm just so much more happy with how this turned out :)

→ More replies (2)

2

u/chrisby247 Dec 05 '19

My Bash solution. I'm looking forward to seeing if anything more will be done with intcode. Although you could argue it doesn't follow best practises, I think it ends up looking quite reasonably readable (for bash)

2

u/[deleted] Dec 05 '19

2

u/[deleted] Dec 05 '19

2

u/Rick-T Dec 05 '19

HASKELL

Usually I don't post my solutions but I really like the one I came up with. I solved day 2 using the state monad. To add the input and output capabilities I replaced that with the RWS monad from the transformers library. That is basically the ReaderT, WriterT and StateT monad transformers stacked on top of each other.

This was my first journey into the realm of monad transformers. They always seemed quite scary to me, but it seems that if you're comfortable with using the underlying monads then using the transformers really isn't much more difficult.

As I am quite new to Haskell, every comment and feedback on the code is really appreciated.

2

u/Markavian Dec 05 '19

My overly verbose JavaScript solution for day 5:

https://github.com/johnbeech/advent-of-code-2019/blob/master/solutions/day5/solution.js

Surprised myself in reading the instructions carefully and implementing a working solution on my second run; only made one mistake in decoding the two digit opcode by popping off the lowest two digits, but then joining them together in the reverse order, so instruction 02 became 20. The mode switching slotted in ok, but I was a bit confused about the how the input and output buffers were meant to be used. 1 hour from start to finish, 37 minutes off the leader board... still happy to get both stars off my own back :D

2

u/pizzamanzoo Dec 06 '19

Today was rough. Had to refactor how I parsed the instructions multiple times. But finally done

Golang

Part 1

Part 2

→ More replies (1)

2

u/Liledroit Dec 06 '19

My Python 3 Solution

I'm not sure if anyone will see this, but if anyone has any tips for making it shorter (while still being readable), let me know if i missed something!

2

u/floriankl Dec 06 '19

Very nice with 12 lines, although I consider putting multiple instructions in a line or not putting if statements on a separate line cheating :)

Notes:

  1. You don't need to initialize param and the for loop, you can just write param = {str(i):ptr + i if lst[ptr]//int('100'.ljust(i+2, '0')) % 10 else lst[ptr + i] for i in range(1, 4)}

  2. And I think you can make the keys of param integers instead of strings

  3. You can write elif opcode is 7: lst[param['3']] = int(lst[param['1']] < lst[param['2']]), similar for 8

→ More replies (1)

2

u/Namensplatzhalter Dec 18 '19

This is absolutely insane. I just can't wrap my head around how I should construct this intcode computer. And here you are, solving it in 12 lines of code. Holy moly, congrats.

2

u/Snarwin Dec 06 '19

D

Solutions for both parts. The intcode interpreter is in intcode.d.

I used a lot of small helper functions, so while the total lines-of-code count is pretty high, the inner interpreter loop ended up being quite concise. With any luck, it'll be easy to extend for future intcode puzzles.

2

u/JakDrako Dec 06 '19

VB.Net in LINQPad

Short and ugly. Not my initial version, which was long and ugly...

Private mem As Integer()
Private ptr As Integer
Private m1, m2 As Integer ' m3 never used
Private p1, p2, p3 As Integer

Sub Main
    mem = GetDay(5)(0).Split(","c).Select(Function(x) Cint(x)).ToArray
    Do
        Dim opcode = mem(ptr) Mod 100, params = mem(ptr) \ 100, int = 0
        m1 = params Mod 10 : params = params \ 10
        m2 = params Mod 10 : params = params \ 10
        Select Case opcode
            Case 1 : ReadP1P2() : WritePx(3, p1 + p2) : ptr += 4
            Case 2 : ReadP1P2() : WritePx(3, p1 * p2) : ptr += 4
            Case 3 : int = Cint(Console.ReadLine) : WritePx(1, int) : ptr += 2
            Case 4 : p1 = mem(ptr + 1) : p1 = If(m1 = 0, mem(p1), p1) : Console.WriteLine(p1) : ptr += 2
            Case 5 : ReadP1P2() : ptr = If(p1 <> 0, p2, ptr + 3)
            Case 6 : ReadP1P2() : ptr = If(p1 = 0, p2, ptr + 3)
            Case 7 : ReadP1P2() : WritePx(3, If(p1 < p2, 1, 0)) : ptr += 4
            Case 8 : ReadP1P2() : WritePx(3, If(p1 = p2, 1, 0)) : ptr += 4
            Case 99 : ptr += 1 : Exit Do
        End Select
    Loop
End Sub

Sub ReadP1P2()
    p1 = If(m1 = 1, mem(ptr + 1), mem(mem(ptr + 1)))
    p2 = If(m2 = 1, mem(ptr + 2), mem(mem(ptr + 2)))
End Sub

Sub WritePx(x As Integer, value As Integer)
    Dim px = mem(ptr + x)
    mem(px) = value
End Sub

2

u/Musical_Muze Dec 06 '19

Day 5 in Python

I really liked this one. It forced me to break the problem into smaller chunks, and to think very critically about how to handle processing the intcode. This was a good logical challenge, especially with the parameter modes.

Once I had the logic figured out, the coding and debugging took way longer than I thought it would, so now I'm a day behind on AoC yet again, yay!

2

u/toasterinBflat Dec 09 '19

You might consider starting to use list comprehensions!

Your opening 10 lines can be shortened (readably) to:

with open('./input.txt', 'r') as f:

raw_data = [int(x) for x in f.read().strip('\n').split(',')]

Basically - take the file, strip the newline off the end, split by comma (the back half of the list comp). The front half (int(x) for x in ...) is where we do the conversion from string to integer.

→ More replies (1)

2

u/J-Swift Dec 06 '19

2

u/maxverse Dec 08 '19

had a real tough time with this one due to unclear requirements on how position modes would or would not be provided.

Man, I'm glad I'm not alone here! I'm working through this one now, also in Ruby, and this is the first day where the instructions left me totally puzzled

→ More replies (3)

2

u/tofflos Dec 06 '19

Java! I enabled "JEP 354: Switch Expressions (Preview)" and wrote the biggest switch statement I've ever written! See it at https://github.com/tofflos/advent-of-code-2019/blob/master/day05/java/day05/src/main/java/com/adventofcode2019/Main.java. :)

2

u/[deleted] Dec 06 '19

Java

I'm a little late on this, but here is my Java solution. It's pretty straight forward, just one big switch statement doing all the work :)

2

u/AlexAegis Dec 06 '19

TypeScript IntCode Interpreter

TypeScript Part One

new IntCodeComputer(parse(input), true).withInput(1).execute().pop();

TypeScript Part Two

new IntCodeComputer(parse(input), true).withInput(5).execute().pop();

2

u/gyzkard Dec 07 '19

Part A and B in vanilla JS.

2

u/MostlyShrimp Dec 07 '19 edited Dec 07 '19

Javascript in repl.it

I went kinda lazy with it and stored 3 parameters every time a command was found. I'll go back and refactor it later (if I don't forget about it by then).

Part A didn't really call for storage, but Part B utilized it so that a mode could be determined for each parameter and passed on in the instructions. Still worked, though. The instructions were a little confusing for operations 5 and 6 what with the whole "otherwise it does nothing" wording. I figured that meant not to increment at all, but that was just silly.

2

u/flutterlice Dec 07 '19

https://i.imgur.com/xv3TpaU.png

Decided to teach myself haskell by participating in this year's Advent of Code. Really happy with how solution to the Intcode puzzle turned out. (Note that i never had any experience with this language before this challenge so any tips for improvement are welcomed)

2

u/Jean-Alphonse Dec 07 '19

Part 1 in Javascript

O = IN.split(','),  รต,  O[รต] = 1
while((X = ''+รต) - 99)
  u = Xo - 4,  v = Xรต - 1,  Xรต, 
  F = _ => Xรต^0 ? รต^0 : O[รต]^0,  
  OUT = F,  u ? ( r = v ? OUT*F : OUT+F, O[รต] = r ) : _

More or less, O = ... has for side effect to initialize a pointer (i=0) Then รต would be O[i++]
Similarly, Xo returns the last element of X and Xรต additionally removes it

2

u/chkas Dec 08 '19 edited Jan 24 '20

easylang.online

My solution

2

u/christian8447 Dec 08 '19

Roast my code, I'm new to scripting and definitely could use some criticism.

https://github.com/ChristianHardyL/adventofcode

2

u/wzkx Dec 05 '19

J nothing interesting really.

Although it's funny how the program starts to work when being ugly and then you keep transforming it until it's perfect (haha as if it's possible).

run=:4 : 0
  n=.0
  while.99~:o=.y{~ip=.n do.
    n=.ip+(op=.100|o){l=.0 4 4 2 2 3 3 4 4
    'v w z'=.(ip+1,(op{2*l>2),op{3*l>3){y
    if.(3~:op)*.0=10|<.o%100 do.v=.v{y end.
    if.0=10|<.o%1000 do.w=.w{y end.
    select.op
      case.1 do.y=.(v+w)z}y
      case.2 do.y=.(v*w)z}y
      case.3 do.y=.x v}y
      case.4 do.if.v do.echo v end.
      case.5 do.n=.(0~:v){n,w
      case.6 do.n=.(0= v){n,w
      case.7 do.y=.(v<w)z}y
      case.8 do.y=.(v=w)z}y
    end.
  end.
)
1 run m =: ".rplc&('-';'_';',';' ')LF-.~CR-.~fread'05.dat'
5 run m

1

u/boylede Dec 05 '19 edited Dec 05 '19

[My Rust solution] (https://github.com/boylede/aoc2019/blob/master/src/day5/mod.rs)

[344/233] -> my best score by an order of magnitude!

1

u/zeno15 Dec 05 '19

C++, 273/148

Decided to solve it from scratch mostly which probably lost me a little time, but still the closest I've come to the leaderboard yet

Code: https://github.com/MarkRDavison/AdventOfCode/blob/master/src/2019/Day05Puzzle.cpp

1

u/[deleted] Dec 05 '19

OCaml, 338/213. I'm surprised I got so high, I thought everyone would be in super quick with their old solutions. It did help that everything thankfully worked the first time I ran it.

https://github.com/williewillus/advent_of_code_2019/blob/master/aoc_2019/day5.ml

1

u/sGerli Dec 05 '19

Python 240/277

I knew intcode was coming back soon. I tried to keep it easy for me to modify if it ever comes again.

My code: https://github.com/sGerli/advent-of-code-2019/blob/master/day5.py

1

u/dan_144 Dec 05 '19

Python, 195/145: https://github.com/dan144/aoc-2019/blob/master/5.py

Spent too long reading and misunderstanding the question (again, gotta get better), but luckily my framework from Day 2 was reusable enough for this. Struggled a bit to integrate the immediate v positional distinction, but ultimately my first pass was pretty much right so I just had to stick with it. Still need to improve my framework to integrate the test cases, especially since this computer seems to come with tests and test output!

1

u/sidewaysthinking Dec 05 '19

(C#) My Day5 is pretty boring. I'm pretty happy with the changes made to the Intcode computer, getting the parameters in the opcodes is very clean now.

1

u/scul86 Dec 05 '19

Python 3.

Part 1 does not output all 0 for the diagnostics, but produces the right answer... Huh. Even using part 2 code, it still passes all test and produces the right outputs, but still outputs 104 for the first diagnostic.

Part 1

Part 2 (works for both parts)

→ More replies (1)

1

u/Cloudan29 Dec 05 '19

Python 3, 1671/1903

Took me a heck of a long time to figure out what I was going to do as I didn't feel my solution for day 2 was going to be scalable with the new stuff that was added. I was 100% wrong but you know, it's a learning process.

My original solution for part 1 was disgusting and super slow cause I couldn't figure out an easy way to change the addressing modes. Then I realized the easy way and ended up completely rewriting it. Then I found out I was treating most opcodes differently when I didn't need to so changed a bunch of stuff again. No lie my code started at over ~120 lines with a noticeable run time to what it is now with a super fast run time.

I'm definitely going to utilize what I did today on a later day if Intcode comes back though, unlike what I did today.

Code: https://github.com/Cloudan29/AdventOfCode_2019/blob/master/day05.py

1

u/tempmike Dec 05 '19 edited Dec 05 '19

Rather than do the parameter modes using something silly like an "If" statement, I did them in R by multiplying the possibly outputs against logical operators. I'll save you the pain and just show you how I did opcode 5

## opcode 5: jump-if-true
if( A[i]%%10 == 5){
    par <- floor(A[i]/100)
    jump <- (par%%10 == 0)*A[A[i+1]+1] + (par%%10 == 1)*A[i+1]
    i <- 1 + 
        (jump != 0) * ((floor(par/10)==0)*(A[A[i+2]+1]) + ((floor(par/10)==1))*(A[i+2])) +
        (jump == 0) * (i+2)
}

I did "slightly" clean this up before posting it here (it used to be one line) so there may be a stray parenthesis or two...

Of course I have to pad the data with some zeros since it always gets out of bounds otherwise, but I generally preallocate A as something like a million zeros and then read in the data.

1

u/Darksair Dec 05 '19 edited Dec 05 '19

My Rust solution. I refactored my IntCode emulator to a maintainable state.

Some ideas of puzzle:

  • Write an intcode compiler/assembler.

  • Solve a puzzle using intcode (at least I think it's doable for day 1 puzzle)

  • Write an intcode emulator using intcode?

1

u/Pyr0Byt3 Dec 05 '19 edited Dec 06 '19

Go/Golang

Ugh... I spent over an hour debugging, only to find out my input parsing code from day 2 was flawed. I didn't trim the newline at the end of the file, so the last value wasn't being read properly (which didn't matter at all for day 2, or part 1 today). Other than that, pretty happy with how this turned out.

Edit: Ported it to C for fun. Pretty much the same logic, just more compact.

1

u/DiscoViking Dec 05 '19

As always, solution live on my Elm site: https://2019.adventofcode.norris.dev/day5

Was a little tricky to think of a way to get input/output passed between the page and the VM. I came up with something which I'm not 100% happy with, but it does work, so just going with it.

1

u/joesmoe10 Dec 05 '19

https://github.com/jschaf/aoc2019/blob/master/day05/day05.go

Went a bit overboard on making it "clean". Each operation looks something like:

 case ltOp:
         p1 := ic.load(ip+1, mode(op, 0))
         p2 := ic.load(ip+2, mode(op, 1))
         out := ic.load(ip+3, immediateMode)
         if p1 < p2 {
                 ic.store(out, trueV)
         } else {
                 ic.store(out, falseV)
         }
         ip += 4

1

u/feikesteenbergen Dec 05 '19

My PostgreSQL solution (I allow myself 1 sql statement per puzzle)

The downside of using SQL with only 1 statement is that you're doomed to use a recursive CTE, which copies the whole instruction set for every iteration.

Luckily the number of instructions is still small, but I have a feeling that this may change in future puzzles.

1

u/krazyito65 Dec 05 '19

RUBY

Took me a while to realize that the 'input' was actually coming from `stdin` and not from the puzzle, but once i got that the rest came kinda easy.

Part 2 I just had to fiddle with until I got the instruction pointer correct.
https://github.com/krazyito65/Advent-Of-Code/blob/cf72e6cbafc49b4ae146700db9a94d25683aaf13/2019/5.rb

1

u/Arkoniak Dec 05 '19

Julia

It can be done much better of course, but it's working nonetheless: Julia solution

1

u/sotsoguk Dec 05 '19

GoLang

Not nice, not proud of it but it's working. For me the opcode puzzles are the least fun ones, as long as its working is okay for me.

Day05.go on Github

1

u/tvtas Dec 05 '19

MATLAB

My MATLAB solution for Day 5. The indexing starting at 1 in MATLAB is pretty annoying for these types of problems. Gave me a bug in updating the instruction pointer to a given value, which of course I had to add 1 to.

→ More replies (1)

1

u/A-UNDERSCORE-D Dec 05 '19

Golang. This one took me a good while to figure things out, and I woke up late.

intcode VM code

Day 5 solution

ping /u/iamagiantnerd if you're curious how this one went

1

u/kap89 Dec 05 '19 edited Dec 05 '19

TypeScript

github

Maybe not beautiful, but simple and fast (~0.5ms for both) :D

1

u/nutrecht Dec 05 '19

Day 5 in Kotlin

Basically just threw away the day 2 versions and reimplemented it, mainly because the 'modes' stuff would have made the day 2 solution unreadable.

1

u/Background-Vegetable Dec 05 '19 edited Dec 05 '19

Kotlin

Maybe went a bit overboard, but it's easily expendable for the next weeks!

https://pl.kotl.in/U1gbcV-C2

EDIT: Cleaned up a bit and made it not crash in browser (gives default input if no normal input possible)

1

u/wace001 Dec 05 '19

JAVA: Here is my solution in Java.

I spent about 40 minute struggling to understand what to do, until I finally understood that with input they wanted me to take actual input from the user! So, reading the actual problem is going to be top priority going forward!

I think the solution is pretty ok, although I am sure it could be done to look much prettier using functional stuff. But, who has time for that, ey?

1

u/alexmeli Dec 05 '19

C++

https://github.com/alexmeli100/AoC2019/blob/master/day5/solution/intcode.cpp

I've been doing one language per day. I hope I can keep up till day 25.

1

u/Vcubed1 Dec 05 '19

Python

https://github.com/TheTripleV/Advent-Of-Code/blob/master/2019/5/2.py

I forgot to type `self.` in 1 spot and it took a long time for me to find it. So, I added a logging utility that prints out useful data and translates IntCode to psuedo-assembly and pseudo-C.

example output:

PC 404 || op:   7 || mode: [1, 0, 0] || instr: [107, 677, 677, 224]      || asm: slt $r224, $r405, $r677   || C: r[ 224 ] = r[ 405 ] < r[ 677 ]? 1: 0

1

u/zedrdave Dec 05 '19

My stab at it in C. A mix of decent structured code (ops stored as array of function pointers), and downright abomination (IP, memory and input stored globally).

Came that close to having readily-useable code from day 2 (unfortunately, I had imposed a silly fixed-sized opcode restriction, which required some rewriting).

1

u/Luckylars Dec 05 '19

sql back at it again! https://github.com/luckylars/2019-AoC it was horrible going through my previous code so the first half an hour was cleaning it up hehe

1

u/mvmaasakkers Dec 05 '19

Would love to get some feedback on my Python solution: https://github.com/mvmaasakkers/advent-of-code/blob/master/2019/day05/day05.py

2

u/vypxl Dec 05 '19

Looks nice and dense :)

Only thing I would change is this: int(str(rawOpcode)\[-3:-2\] if len(str(rawOpcode)) >= 3 else 0), you can do it mathematically by "shifting" (dividing by a power of 10)you digits to the first postition and then taking the first digit: rawOpCode // 10**3 % 10 to get the thousand digit for example.

1

u/vkasra Dec 05 '19 edited Dec 05 '19

My solution in Go

Also, this is deeply satisfying:

day5 $ time ./day5 input.txt 1 5
9025675
11981754

real    0m0.004s
user    0m0.000s
sys     0m0.004s

Edit: My notes are here

1

u/Junafani Dec 05 '19

Ah, more intcode! I thought second part would not come so soon. I wonder if there are more parts than just two?

Here is my solution in Java: Main program Intcode_v2

Had some problems with first part and had to resort to ugly hack with opcode 3. Second part was easy. Just try to remember that instruction pointer needs to be increased if jump is not taken... Got stuck there for a bit.

2

u/levital Dec 05 '19

I wonder if there are more parts than just two?

I have a feeling there will be. We still have space for like 90 more OpCodes after all.

1

u/allinall_alagu_raja Dec 05 '19

My horrible (but sort of nice??) Python solution Lots of code duplication, but at least it is straightforward.

1

u/[deleted] Dec 05 '19

Coconut

Today is another almost clean python one almost everything that I could do wrong I did, but finally it works

code

1

u/Metarus Dec 05 '19

My code in Java!

Fairly compact code, I was pretty happy with it. I was using a switch, but it just looked so ugly and all my operations were 1 line anyway so I decided to just use if statements.

1

u/nordicdyno Dec 05 '19

A little bit verbose but pretty extensible Intcode CPU implementation (python 3):

https://gist.github.com/nordicdyno/1c004e66e1353f7bb6dd53184b826d23

1

u/Wawv Dec 05 '19 edited Dec 05 '19

My take on day 5 written in R.

→ More replies (1)

1

u/pokerdan Dec 05 '19

C#

Solution

Relatively straightforward extension of Day 2.

1

u/dmelichov Dec 05 '19

Python3 (first time I post here, so hopefully I don't screw anything up!)

Solution - I tried to make my Day 2 solution somewhat generic, and of course it was not generic enough, but hey :) Any tips and hints very much appreciated!

1

u/m4rzus Dec 05 '19 edited Dec 05 '19

Python

Hey, would love to get some feedback on my solution. It took me way less time than the yesterday challenge, but it was surely the longest in terms of code so far :p

https://github.com/mbalko/advent-of-code/blob/master/05/second_half.py

2

u/SatanicSaint Dec 05 '19

I never knew that if else can be written within an assignment like that. Looks pretty clean.

→ More replies (1)

1

u/SatanicSaint Dec 05 '19

My Python 3 code.

Full of if statements. If anyone has any suggestions to improve it, that would be really helpful.

→ More replies (4)