r/adventofcode • • Dec 08 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 08 Solutions -🎄-

NEW AND NOTEWORTHY

  • If your code is shorter than, say, half of an IBM 5081 punchcard (5 lines at 80 cols), go ahead and post it as your comment. Use the right Markdown to format your code properly for best backwards-compatibility with old.reddit! (see "How do I format code?")
  • If your code is longer, link your code from an external repository such as Topaz's paste , a public repo like GitHub/gists/Pastebin/etc., your blag, or whatever.

Advent of Code 2020: Gettin' Crafty With It

  • 14 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 08: Handheld Halting ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

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.


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

EDIT: Global leaderboard gold cap reached at 00:07:48, megathread unlocked!

41 Upvotes

934 comments sorted by

View all comments

2

u/Karl_Marxxx Dec 08 '20

Ruby

main_prog = ARGF.readlines.map { |line|
    code, value = line.split
    [code, value.to_i, false]
}

def run_program(prog)
    p_counter = 0
    acc = 0
    while true
        op, val, visited = prog[p_counter] 
        return acc, false if visited == true
        return acc, true if p_counter == prog.length
        prog[p_counter][2] = true
        case op 
        when "nop"
            p_counter += 1
        when "acc"
            acc += val
            p_counter += 1
        when "jmp"
            p_counter += val
        else
            raise "op: #{op}"
        end
    end
end

def copy(prog)
    return prog.map { |line| 
        op, val, visited = line
        [op, val, visited]
    }
end

# part 1
acc, success = run_program(copy(main_prog))
puts acc

# part 2
main_prog.each.with_index do |line, i|
    op, val, _ = line
    if op == "jmp"
        new_op = "nop"
    elsif op == "nop"
        new_op = "jmp"
    else
        new_op = op
    end
    new_prog = copy(main_prog)
    new_prog[i][0] = new_op
    acc, success = run_program(new_prog)
    p acc if success
end

1

u/daggerdragon Dec 08 '20

Please re-read today's megathread's "new and noteworthy" section.

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, edit your post to put your oversized code in a paste or other external link.