예제 #1
0
def day07PartTwo():
    thrusterDict = {}
    amplifierController = getInputData()
    for seq in itertools.permutations([5, 6, 7, 8, 9], 5):
        print(f'----- {seq} -----')
        ICA = IntcodeComputer(amplifierController)
        ICB = IntcodeComputer(amplifierController)
        ICC = IntcodeComputer(amplifierController)
        ICD = IntcodeComputer(amplifierController)
        ICE = IntcodeComputer(amplifierController)
        signal = runOneSeq(ICA, ICB, ICC, ICD, ICE, seq)
        print(f'-  {signal}  -')
        thrusterDict[seq] = signal

    maxSetting = max(thrusterDict, key=thrusterDict.get)
    maxSignal = max(thrusterDict.values())
    print(thrusterDict)
    print(maxSetting)
    print(maxSignal)

    print(
        f'Solution Day 07, Part two:\nAnswer: Amp.dettings:{maxSetting} --> signal:{maxSignal},  \n\n'
    )

    return signal
예제 #2
0
def part2(amp_controller_code: List[int]) -> int:
    output_signals = []
    input_a = 0
    for phase_setting_sequence in permutations(range(5, 10), 5):
        a, b, c, d, e = phase_setting_sequence
        amp_computers = [
            IntcodeComputer(amp_controller_code, inputs=[a]),  # amp a
            IntcodeComputer(amp_controller_code, inputs=[b]),  # amp b
            IntcodeComputer(amp_controller_code, inputs=[c]),  # amp c
            IntcodeComputer(amp_controller_code, inputs=[d]),  # amp d
            IntcodeComputer(amp_controller_code, inputs=[e])   # amp e
        ]
        output = 0
        while True:
            return_codes = []
            for amp_comp in amp_computers:
                amp_comp.set_inputs([output])
                return_code, return_value = amp_comp.execute()
                if return_code == IntcodeComputer.RETURNING_OUTPUT:
                    output = return_value
                return_codes.append(return_code)
            if [IntcodeComputer.HALT] * 5 == return_codes:
                break

        output_signals.append(output)

    return max(output_signals)
예제 #3
0
	def __init__(self, file=None, echo=True):
		if file is None:
			self.computer = IntcodeComputer(echo=echo)
		else:
			self.computer = IntcodeComputer(file, echo=echo)

		self.width, self.height = 0, 0
		self.grid = []
예제 #4
0
def test_equal():
    # position output
    computer = IntcodeComputer([1108, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[2] == 0

    # relative
    computer = IntcodeComputer([109, -1, 21108, 3, 5, 3, 99])
    computer.execute()
    assert computer.program[2] == 0
예제 #5
0
def test_multiplication():
    # position output
    computer = IntcodeComputer([1102, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[2] == 15

    # relative
    computer = IntcodeComputer([109, 2, 21102, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[4] == 15
예제 #6
0
def test_less_than():
    # position output
    computer = IntcodeComputer([1107, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[2] == 1

    # relative
    computer = IntcodeComputer([109, -1, 21107, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[1] == 1
예제 #7
0
    def __init__(self, input_file=None, echo=True):
        if input_file:
            self.computer = IntcodeComputer(input_file, echo=echo)
        else:
            self.computer = IntcodeComputer(echo=echo)

        # 0 UP, 1 RIGHT, 2 DOWN, 3 LEFT
        self.direction = 0
        self.position = (0, 0)
        self.painted_tiles = {}
        self.echo = echo
예제 #8
0
def test_get_value_relative():
    # base += 3 (immediate), output in relative mode
    computer = IntcodeComputer([109, 3, 204, 1, 99])
    code, result = computer.execute()
    assert computer.relative_base == 3
    assert result == 99

    computer = IntcodeComputer([109, 19, 204, -34, 99] +
                               [n for n in range(5, 1996)])
    computer.relative_base = 2000
    code, result = computer.execute()
    assert computer.relative_base == 2019
    assert result == 1985
예제 #9
0
def test_adjust_relative_base():
    computer = IntcodeComputer()
    assert computer.relative_base == 0

    # immediate mode
    computer = IntcodeComputer([109, 5, 99])
    computer.execute()
    assert computer.relative_base == 5

    # position mode
    computer = IntcodeComputer([9, 3, 99, -7])
    computer.execute()
    assert computer.relative_base == -7
예제 #10
0
def test_part_2_puzzle():
    intcode_list = list(map(int, open('input.txt').read().split(',')))

    best_value = 0
    best_phase_setting = None
    for phase_setting in permutations(range(5, 10)):
        computers = [IntcodeComputer(intcode_list) for i in range(5)]

        for phase, computer in zip(phase_setting, computers):
            computer.input_list.append(phase)

        current_value = 0
        while computers[-1].halt_flag != True:
            for i, computer in enumerate(computers):
                try:
                    for output_value in computer.execute(current_value):
                        current_value = output_value
                except IndexError:
                    pass
        final_output = current_value
        if final_output > best_value:
            best_value = final_output
            best_phase_setting = phase_setting

    assert best_value == 4931744
예제 #11
0
def runRobot(instructions):
    robotController = getInputData()
    IC = IntcodeComputer(robotController)
    IC.run_program(instructions)
    outCode = IC._output
    # print(ascii2str(outCode))
    return ascii2str(outCode)
예제 #12
0
def part_two():
    max_output = 0
    this_intcode = [x for x in intcode]
    for phases in permutations(range(5, 10)):
        intcom_input = 0
        intcoms = [
            IntcodeComputer(intcode=this_intcode,
                            intcode_input=phase,
                            designation=phases.index(phase))
            for phase in phases
        ]
        while (intcoms[0].computer_state() != "halted"
               or intcoms[1].computer_state() != "halted"
               or intcoms[2].computer_state() != "halted"
               or intcoms[3].computer_state() != "halted"
               or intcoms[4].computer_state() != "halted"):
            for intcom in intcoms:
                if intcom_input != None:
                    intcom.new_input(intcom_input)
                    intcom_input = None
                while (intcom.computer_state() == "running"):
                    intcom.execute_opcode()
                intcom_input = intcom.new_output()
        if intcom_input > max_output:
            max_output = intcom_input
    print(max_output)
예제 #13
0
	def run(self):
		self.computers = [IntcodeComputer(self.file_str, echo=False) for _ in range(50)]
		self.setup_network_addresses()

		input_queue = [[] for computer in self.computers]

		running = True
		while running:
			for i, computer in enumerate(self.computers):
				input = input_queue[i]
				if len(input) > 0:
					computer.read_input(input)
					input.clear()
				else:
					computer.read_input(-1)
					computer.run()

				output = computer.get_output()

				while len(output) > 0:
					address = output[0]
					x = output[1]
					y = output[2]

					if address != 255:
						input_queue[address].extend([x, y])
						output = output[3:]
					else:
						return (x, y)
예제 #14
0
    def test_addition_and_multiplication_opcode(self):
        prog = IntcodeComputer()
        sample_op = [1, 1, 1, 4, 99, 5, 6, 0, 99]
        expectation = [30, 1, 1, 4, 2, 5, 6, 0, 99]

        result = prog.compute_sequence(sample_op)
        self.assertEqual(result, expectation)
예제 #15
0
def day05PartTwo():
    prg2 = getInputData()
    IntCode2 = IntcodeComputer(prg2)
    print(
        f'Solution Day 05, Part two:\nRunning TEST diagnostic program...\nGive manual input=>5\n'
    )
    IntCode2.run_program()
예제 #16
0
def cameraOutput(defaultColor=0):
    code = getInputData()
    IC = IntcodeComputer(code)

    step = 0
    inp = []
    IC._output = []  # Clear the output list
    terminate = False
    stoppedAtInput = False
    while not terminate:
        while not stoppedAtInput and not terminate:
            terminate, stoppedAtInput = IC.perform_one_operation(
                IC._memoryPosition, inp, stopAtInput=True)
        step += 1
        # print(f'### STEP {step} ###')
        # print(f'OutPut{IC._output}')
        # print(f'OutPut{IC._output}')
        stoppedAtInput = False

    ret = decodeMap(IC._output)
    # ret = []
    # row = ''
    # for ascii in IC._output:
    #     if str(ascii) == '10':
    #         ret.append(row)
    #         row = ''
    #     else:
    #         row += chr(ascii)
    return ret
예제 #17
0
def collect_dust(memory, main, functions, continuous_video_feed=False):
    memory[0] = 2

    inputs = main + functions[0] + functions[1] + functions[2] + [121 if continuous_video_feed else 110, 10]
    intcode_computer = IntcodeComputer(memory, initial_inputs=inputs)
    intcode_computer.run()
    return intcode_computer.get_all_outputs()
예제 #18
0
def part1(program: List[int]) -> int:
    computer = IntcodeComputer(program, [1])

    while True:
        code, result = computer.execute()
        if code == IntcodeComputer.RETURNING_OUTPUT:
            return result
예제 #19
0
    def test_multiplication_opcode(self):
        prog = IntcodeComputer()
        sample_op = [2, 3, 0, 3, 99]
        expectation = [2, 3, 0, 6, 99]

        result = prog.compute_sequence(sample_op)
        self.assertEqual(result, expectation)
예제 #20
0
    def test_addition_opcode(self):
        prog = IntcodeComputer()
        sample_op = [1, 0, 0, 0, 99]
        expectation = [2, 0, 0, 0, 99]

        result = prog.compute_sequence(sample_op)
        self.assertEqual(result, expectation)
예제 #21
0
def test_part_2_example_2():
    intcode_list = [
        3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005,
        55, 26, 1001, 54, -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55,
        1001, 55, 1, 55, 2, 53, 55, 53, 4, 53, 1001, 56, -1, 56, 1005, 56, 6,
        99, 0, 0, 0, 0, 10
    ]

    final_value = 0
    phase_setting = (9, 7, 8, 5, 6)
    computers = [IntcodeComputer(intcode_list) for i in range(5)]

    for phase, computer in zip(phase_setting, computers):
        computer.input_list.append(phase)

    current_value = 0
    while computers[-1].halt_flag != True:
        for i, computer in enumerate(computers):
            try:
                for output_value in computer.execute(current_value):
                    print(output_value)
                    current_value = output_value
            except:
                pass
        final_value = current_value
    assert final_value == 18216
예제 #22
0
def paint_hull(program, start_color):
    computer = IntcodeComputer(program)
    # NESW
    direction = 0
    position = (0, 0)
    panel_colors = defaultdict(int)
    panel_colors[position] = start_color
    panels_painted = 1

    def new_direction(turn_right: int):
        if turn_right:
            return (direction + 1) % 4
        else:
            return (direction - 1) % 4

    while not computer.run(panel_colors[position]):
        paint_color = computer.outputs[-2]
        turn_right = computer.outputs[-1]
        panel_colors[position] = paint_color
        direction = new_direction(turn_right)
        position = update_position(position, direction)
        if position not in panel_colors:
            panels_painted += 1

    return panels_painted, panel_colors
예제 #23
0
def part2(program: List[int]) -> None:
    paint_bot = IntcodeComputer(program)
    ship_hull = paint_hull(paint_bot, {(0, 0): 1})

    # get canvas dimensions based on visited hull locations
    max_x, _ = max(ship_hull.keys(), key=lambda p: p[0])
    min_x, _ = min(ship_hull.keys(), key=lambda p: p[0])
    _, max_y = max(ship_hull.keys(), key=lambda p: p[1])
    _, min_y = min(ship_hull.keys(), key=lambda p: p[1])

    width = abs(max_x) + abs(min_x)
    height = abs(max_y) + abs(min_y)

    canvas = [[0 for _ in range(width + 1)] for _ in range(height + 1)]

    # color the canvas according to hull colors
    for (x, y), color in ship_hull.items():
        canvas[y - min_y][x - min_x] = color

    COLORS = {0: "█", 1: " "}

    # print the canvas
    for row in reversed(canvas):
        for char in row:
            print(COLORS[char], end="")
        print()
예제 #24
0
    def test_day7_1(self):

        for name, memory in [
            ('Day 7 test 1', self.DAY_7_MEMORY_1),
            ('Day 7 test 2', self.DAY_7_MEMORY_2),
            ('Day 7 test 3', self.DAY_7_MEMORY_3),
        ]:

            computer = IntcodeComputer(memory)
            best_phase_settings = None
            best_phase_output = -99999999
            initial_input = 0

            for phase_settings in list(permutations([0, 1, 2, 3, 4])):

                next_input = initial_input
                for phase in phase_settings:
                    computer.reset()
                    next_input = computer.run(phase, next_input)
                if next_input > best_phase_output:
                    best_phase_settings = phase_settings
                    best_phase_output = next_input

            with self.subTest(f'{name}'):
                expected_phase_setting, expected_outcome = self.DAY_7_EXPECTED_OUTCOMES[
                    name]
                self.assertEqual(best_phase_settings, expected_phase_setting)
                self.assertEqual(best_phase_output, expected_outcome)
예제 #25
0
def day05PartOne():
    prg = getInputData()
    IntCode = IntcodeComputer(prg)
    print(
        f'Solution Day 05, Part one:\nRunning TEST diagnostic program...\nGive manual input=>1\n'
    )
    IntCode.run_program()
예제 #26
0
 def test_day9_1(self):
     data = {
         "day 9 part 1 - 1": {
             'memory': [
                 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101,
                 1006, 101, 0, 99
             ],
             'expected_output': [
                 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101,
                 1006, 101, 0, 99
             ]
         },
         "day 9 part 1 - 2": {
             'memory': [1102, 34915192, 34915192, 7, 4, 7, 99, 0],
             'expected_output': 1219070632396864
         },
         "day 9 part 1 - 3": {
             'memory': [104, 1125899906842624, 99],
             'expected_output': 1125899906842624
         }
     }
     for name in data.keys():
         computer = IntcodeComputer(data[name]['memory'])
         test_output = computer.run()
         expected_output = data[name]['expected_output']
         with self.subTest(name):
             self.assertEqual(expected_output, test_output)
예제 #27
0
def test_take_input():
    # position
    computer = IntcodeComputer([3, 0, 99], inputs=[1])
    computer.execute()
    print(computer.program)
    assert computer.program[0] == 1

    # immediate
    computer = IntcodeComputer([103, 5, 99], inputs=[4])
    computer.execute()
    assert computer.program[1] == 4

    # relative to 1, relative input to 1 is memory location 2
    computer = IntcodeComputer([9, 1, 203, 1, 99], inputs=[5])
    computer.execute()
    assert computer.program[2] == 5
예제 #28
0
    def test_another_multiplication_opcode(self):
        prog = IntcodeComputer()
        sample_op = [2, 4, 4, 5, 99, 0]
        expectation = [2, 4, 4, 5, 99, 9801]

        result = prog.compute_sequence(sample_op)
        self.assertEqual(result, expectation)
예제 #29
0
def test_addition():
    # position output
    computer = IntcodeComputer([1101, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[2] == 8

    # immediate
    computer = IntcodeComputer([11101, 3, 5, 2, 99])
    computer.execute()
    assert computer.program[3] == 8

    # relative
    computer = IntcodeComputer([109, -2, 21101, 5, 7, 4, 99])
    computer.execute()
    assert computer.relative_base == -2
    assert computer.program[2] == 12
예제 #30
0
def solution():
    from pathlib import Path
    input_file = Path(INPUT_FILE)

    program = parse_program(input_file)
    computer = IntcodeComputer(program=None)

    amp_A = Amplifier(computer, program)
    amp_B = Amplifier(computer, program)
    amp_C = Amplifier(computer, program)
    amp_D = Amplifier(computer, program)
    amp_E = Amplifier(computer, program)

    # compose the Chain of Responsibility
    amp_A.set_successor(amp_B)
    amp_B.set_successor(amp_C)
    amp_C.set_successor(amp_D)
    amp_D.set_successor(amp_E)

    base_config = [0, 1, 2, 3, 4]    # basic configuration
    amp_list = [amp_A, amp_B, amp_C, amp_D, amp_E]

    signal_outputs = []
    for phase_config in itertools.permutations(base_config, len(base_config)):
        set_phases(amp_list, phase_config)
        signal_outputs.append(amp_A.get_output_signal())

    return max(signal_outputs)