~charles/misc

7fdd3d604a013f07f818e62beb5d844300001f63 — Charles Daniels a month ago 0bf4507
complete day 2
7 files changed, 657 insertions(+), 1 deletions(-)

A advent2019/day2.txt
A advent2019/day2_input.txt
A advent2019/day2_sample.txt
A advent2019/day2p1.go
A advent2019/day2p1_better.go
A advent2019/day2p2.go
D advent2019/temp.txt
A advent2019/day2.txt => advent2019/day2.txt +73 -0
@@ 0,0 1,73 @@
--- Day 2: 1202 Program Alarm ---

On the way to your gravity assist around the Moon, your ship computer beeps angrily about a "1202 program alarm". On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The ship computer bursts into flames.

You notify the Elves that the computer's magic smoke seems to have escaped. "That computer ran Intcode programs like the gravity assist program it was working on; surely there are enough spare parts up there to build a new Intcode computer!"

An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at the first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; for example, 99 means that the program is finished and should immediately halt. Encountering an unknown opcode means something went wrong.

Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers immediately after the opcode tell you these three positions - the first two indicate the positions from which you should read the input values, and the third indicates the position at which the output should be stored.

For example, if your Intcode computer encounters 1,10,20,30, it should read the values at positions 10 and 20, add those values, and then overwrite the value at position 30 with their sum.

Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.

Once you're done processing an opcode, move to the next one by stepping forward 4 positions.

For example, suppose you have the following program:

1,9,10,3,2,3,11,0,99,30,40,50

For the purposes of illustration, here is the same program split into multiple lines:

1,9,10,3,
2,3,11,0,
99,
30,40,50

The first four integers, 1,9,10,3, are at positions 0, 1, 2, and 3. Together, they represent the first opcode (1, addition), the positions of the two inputs (9 and 10), and the position of the output (3). To handle this opcode, you first need to get the values at the input positions: position 9 contains 30, and position 10 contains 40. Add these numbers together to get 70. Then, store this value at the output position; here, the output position (3) is at position 3, so it overwrites itself. Afterward, the program looks like this:

1,9,10,70,
2,3,11,0,
99,
30,40,50

Step forward 4 positions to reach the next opcode, 2. This opcode works just like the previous, but it multiplies instead of adding. The inputs are at positions 3 and 11; these positions contain 70 and 50 respectively. Multiplying these produces 3500; this is stored at position 0:

3500,9,10,70,
2,3,11,0,
99,
30,40,50

Stepping forward 4 more positions arrives at opcode 99, halting the program.

Here are the initial and final states of a few more small programs:

    1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
    2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
    2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
    1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.

Once you have a working computer, the first step is to restore the gravity assist program (your puzzle input) to the "1202 program alarm" state it had just before the last computer caught fire. To do this, before running the program, replace position 1 with the value 12 and replace position 2 with the value 2. What value is left at position 0 after the program halts?


--- Part Two ---

"Good, the new computer seems to be working correctly! Keep it nearby during this mission - you'll probably use it again. Real Intcode computers support many more features than your new one, but we'll let you know what they are as you need them."

"However, your current priority should be to complete your gravity assist around the Moon. For this mission to succeed, we should settle on some terminology for the parts you've already built."

Intcode programs are given as a list of integers; these values are used as the initial state for the computer's memory. When you run an Intcode program, make sure to start by initializing memory to the program's values. A position in memory is called an address (for example, the first value in memory is at "address 0").

Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values used immediately after an opcode, if any, are called the instruction's parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, and 4 are the parameters. The instruction 99 contains only an opcode and has no parameters.

The address of the current instruction is called the instruction pointer; it starts at 0. After an instruction finishes, the instruction pointer increases by the number of values in the instruction; until you add more instructions to the computer, this is always 4 (1 opcode + 3 parameters) for the add and multiply instructions. (The halt instruction would increase the instruction pointer by 1, but it halts the program instead.)

"With terminology out of the way, we're ready to proceed. To complete the gravity assist, you need to determine what pair of inputs produces the output 19690720."

The inputs should still be provided to the program by replacing the values at addresses 1 and 2, just like before. In this program, the value placed in address 1 is called the noun, and the value placed in address 2 is called the verb. Each of the two input values will be between 0 and 99, inclusive.

Once the program has halted, its output is available at address 0, also just like before. Each time you try a pair of inputs, make sure you first reset the computer's memory to the values in the program (your puzzle input) - in other words, don't reuse memory from a previous attempt.

Find the input noun and verb that cause the program to produce the output 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, the answer would be 1202.)


A advent2019/day2_input.txt => advent2019/day2_input.txt +1 -0
@@ 0,0 1,1 @@
1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,13,19,1,9,19,23,1,6,23,27,2,27,9,31,2,6,31,35,1,5,35,39,1,10,39,43,1,43,13,47,1,47,9,51,1,51,9,55,1,55,9,59,2,9,59,63,2,9,63,67,1,5,67,71,2,13,71,75,1,6,75,79,1,10,79,83,2,6,83,87,1,87,5,91,1,91,9,95,1,95,10,99,2,9,99,103,1,5,103,107,1,5,107,111,2,111,10,115,1,6,115,119,2,10,119,123,1,6,123,127,1,127,5,131,2,9,131,135,1,5,135,139,1,139,10,143,1,143,2,147,1,147,5,0,99,2,0,14,0

A advent2019/day2_sample.txt => advent2019/day2_sample.txt +1 -0
@@ 0,0 1,1 @@
1,9,10,3,2,3,11,0,99,30,40,50

A advent2019/day2p1.go => advent2019/day2p1.go +146 -0
@@ 0,0 1,146 @@
/* Copyright 2019 Charles Daniels */

/* Solution for Advent of Code 2019, Day 2, part 1 */

/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 * For more information, please refer to <http://unlicense.org/>
 */

package main

import "fmt"
import "bufio"
import "os"
import "strconv"
// import "math"
import "strings"

/* display a memory dump, 8 locations per line, grouped into two columns of 4 */
func memdump(mem []int64) {
	for i, v := range mem {

		/* every 8th location display an address */
		if (i % 8 == 0) { fmt.Printf("\n%7d:", i); }

		/* split into two columns */
		if (i % 4 == 0) { fmt.Printf("       "); }

		/* display each value */
		fmt.Printf(" %7d ", v);
	}
	fmt.Printf("\n\n");
}

/* read a memory location, crashing if it's out of bounds */
func memread(mem []int64, index int64) int64 {
	if (index >= int64(len(mem))) {
		fmt.Fprintf(os.Stderr, "ERROR: read out of bounds: %d\n", index);
		os.Exit(1);
	}
	return mem[index];
}

/* read a memory location, returning a default value silently if it's out of
 * bounds */
func memreaddefault(mem []int64, index int64, defaultval int64) int64 {
	if (index >= int64(len(mem))) {
		return defaultval;
	} else {
		return mem[index];
	}
}

func main() {
	var mem []int64;

	/* iterate over stdin */
	scanner := bufio.NewScanner(os.Stdin);
	for scanner.Scan() {

		/* tokenize each line on "," */
		tokens := strings.Split(scanner.Text(), ",");
		for _, tok := range tokens {

			/* parse each token to an integer, ignoring errors
			 * silently */
			val, _ := strconv.Atoi(tok);

			/* append to the mem slice */
			mem = append(mem, int64(val));
		}
	}

	memdump(mem);

	/* index into mem */
	cursor := int64(0);

	for true {

		/* extract the values of all operands */
		opcode   := memread(mem, cursor);
		src1     := memreaddefault(mem, cursor+1, 99);
		src2     := memreaddefault(mem, cursor+2, 99);
		dest     := memreaddefault(mem, cursor+3, 99);
		operand1 := memreaddefault(mem, src1, 99);
		operand2 := memreaddefault(mem, src2, 99);

		/* display instruction as read */
		fmt.Printf("%8d, %8d, %8d, %8d   : ", opcode, src1, src2, dest);

		if (mem[cursor] == 99) {		/* halt */
			fmt.Printf("HALT\n");
			fmt.Printf("\nprogram halted at location %d\n", cursor);
			memdump(mem);
			break;

		} else if (opcode == 1) {		/* addition */
			fmt.Printf("mem[%8d] ← %8d + %8d = %8d\n",
				dest,
				operand1,
				operand2,
				operand1 + operand2);

			mem[dest] = operand1 + operand2;

		} else if (mem[cursor] == 2) {		/* multiplication */
			fmt.Printf("mem[%8d] ← %8d * %8d = %8d\n",
				dest,
				operand1,
				operand2,
				operand1 * operand2);

			mem[dest] = operand1 * operand2;

		} else {				/* unknown opcode */
			fmt.Fprintf(os.Stderr, "ERROR: invalid opcode %d\n", mem[cursor]);
			os.Exit(1);
		}
		cursor += 4;
	}
}


A advent2019/day2p1_better.go => advent2019/day2p1_better.go +207 -0
@@ 0,0 1,207 @@
/* Copyright 2019 Charles Daniels */

/* Solution for Advent of Code 2019, Day 2, part 1 */

/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 * For more information, please refer to <http://unlicense.org/>
 */

package main

import "fmt"
import "bufio"
import "os"
import "strconv"
import "strings"

/* status codes */
const (
	STATUS_OK    = iota
	STATUS_FAULT = iota
	STATUS_HALT  = iota
)

/* map status codes to strings */
var STATUS_STRING = map[int]string{
	STATUS_OK:    "OK",
	STATUS_FAULT: "FAULT",
	STATUS_HALT:  "HALT",
};

/* display a memory dump, 8 locations per line, grouped into two columns of 4 */
func memdump(mem []int64) {
	for i, v := range mem {

		/* every 8th location display an address */
		if (i % 8 == 0) { fmt.Printf("\n%7d:", i); }

		/* split into two columns */
		if (i % 4 == 0) { fmt.Printf("       "); }

		/* display each value */
		fmt.Printf(" %7d ", v);
	}
	fmt.Printf("\n\n");
}

/* read a memory location, crashing if it's out of bounds */
func memread(mem []int64, index int64) int64 {
	if (index >= int64(len(mem))) {
		fmt.Fprintf(os.Stderr, "ERROR: read out of bounds: %d\n", index);
		os.Exit(1);
	}
	return mem[index];
}

/* read a memory location, returning a default value silently if it's out of
 * bounds */
func memreaddefault(mem []int64, index int64, defaultval int64) int64 {
	if (index >= int64(len(mem))) {
		return defaultval;
	} else {
		return mem[index];
	}
}

/* run the Intcode CPU by one step */
func step(mem []int64, cursor int64) (int64, int, []string) {

	/* extract the values of all operands */
	opcode   := memread(mem, cursor);

	/* trace, for optional printing */
	var trace []string;

	if (mem[cursor] == 99) {		/* halt */
		trace = append(trace, fmt.Sprintf("%8s\b", "HALT\n"));
		return 0, STATUS_HALT, trace;

	} else if (opcode == 1) {		/* addition */
		src1   := memread(mem, cursor+1);
		src2   := memread(mem, cursor+2);
		dest   := memread(mem, cursor+3);
		param1 := memread(mem, src1);
		param2 := memread(mem, src2);

		t := fmt.Sprintf("%8s, %8d, %8d, %8d:    mem[%8d] ← %8d + %8d = %8d\n",
			"ADD",
			src1,
			src2,
			dest,
			dest,
			param1,
			param2,
			param1 + param2);
		trace = append(trace, t);

		mem[dest] = param1 + param2;

		return cursor + 4, STATUS_OK, trace;

	} else if (mem[cursor] == 2) {		/* multiplication */
		src1   := memread(mem, cursor+1);
		src2   := memread(mem, cursor+2);
		dest   := memread(mem, cursor+3);
		param1 := memread(mem, src1);
		param2 := memread(mem, src2);

		t := fmt.Sprintf("%8s, %8d, %8d, %8d:    mem[%8d] ← %8d * %8d = %8d\n",
			"MULT",
			src1,
			src2,
			dest,
			dest,
			param1,
			param2,
			param1 * param2);
		trace = append(trace, t);

		mem[dest] = param1 * param2;

		return cursor + 4, STATUS_OK, trace;

	} else {				/* unknown opcode */
		t := fmt.Sprintf("ERROR: invalid opcode %d@%d\n", mem[cursor], cursor);
		trace := append(trace, t);
		return 0, STATUS_FAULT, trace;
	}

}

func main() {
	var mem []int64;

	/* iterate over stdin */
	scanner := bufio.NewScanner(os.Stdin);
	for scanner.Scan() {

		/* tokenize each line on "," */
		tokens := strings.Split(scanner.Text(), ",");
		for _, tok := range tokens {

			/* parse each token to an integer, ignoring errors
			 * silently */
			val, _ := strconv.Atoi(tok);

			/* append to the mem slice */
			mem = append(mem, int64(val));


		}
	}

	memdump(mem);

	var cursor int64 = 0;
	var status int;
	var trace []string;

	for true {

		/* execute the next step */
		cursor, status, trace = step(mem, cursor);

		/* display instruction trace for the step */
		for _, line := range trace {
			fmt.Printf("(%8s) %s", STATUS_STRING[status], line);
		}

		/* halt if the status is halt */
		if (status == STATUS_HALT) {
			memdump(mem);
			os.Exit(0);
		}

		/* error if the status is fault */
		if (status == STATUS_FAULT) {
			memdump(mem);
			os.Exit(1);
		}
	}

}


A advent2019/day2p2.go => advent2019/day2p2.go +229 -0
@@ 0,0 1,229 @@
/* Copyright 2019 Charles Daniels */

/* Solution for Advent of Code 2019, Day 2, part 2 */

/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 * For more information, please refer to <http://unlicense.org/>
 */

package main

import "fmt"
import "bufio"
import "os"
import "strconv"
import "strings"

/* status codes */
const (
	STATUS_OK    = iota
	STATUS_FAULT = iota
	STATUS_HALT  = iota
)

/* map status codes to strings */
var STATUS_STRING = map[int]string{
	STATUS_OK:    "OK",
	STATUS_FAULT: "FAULT",
	STATUS_HALT:  "HALT",
};

const TARGETVAL = 19690720;

/* display a memory dump, 8 locations per line, grouped into two columns of 4 */
func memdump(mem []int64) {
	for i, v := range mem {

		/* every 8th location display an address */
		if (i % 8 == 0) { fmt.Printf("\n%7d:", i); }

		/* split into two columns */
		if (i % 4 == 0) { fmt.Printf("       "); }

		/* display each value */
		fmt.Printf(" %7d ", v);
	}
	fmt.Printf("\n\n");
}

/* read a memory location, crashing if it's out of bounds */
func memread(mem []int64, index int64) int64 {
	if (index >= int64(len(mem))) {
		fmt.Fprintf(os.Stderr, "ERROR: read out of bounds: %d\n", index);
		os.Exit(1);
	}
	return mem[index];
}

/* read a memory location, returning a default value silently if it's out of
 * bounds */
func memreaddefault(mem []int64, index int64, defaultval int64) int64 {
	if (index >= int64(len(mem))) {
		return defaultval;
	} else {
		return mem[index];
	}
}

/* run the Intcode CPU by one step */
func step(mem []int64, cursor int64) (int64, int, []string) {

	/* extract the values of all operands */
	opcode   := memread(mem, cursor);

	/* trace, for optional printing */
	var trace []string;

	if (mem[cursor] == 99) {		/* halt */
		trace = append(trace, fmt.Sprintf("%8s\b", "HALT\n"));
		return 0, STATUS_HALT, trace;

	} else if (opcode == 1) {		/* addition */
		src1   := memread(mem, cursor+1);
		src2   := memread(mem, cursor+2);
		dest   := memread(mem, cursor+3);
		param1 := memread(mem, src1);
		param2 := memread(mem, src2);

		t := fmt.Sprintf("%8s, %8d, %8d, %8d:    mem[%8d] ← %8d + %8d = %8d\n",
			"ADD",
			src1,
			src2,
			dest,
			dest,
			param1,
			param2,
			param1 + param2);
		trace = append(trace, t);

		mem[dest] = param1 + param2;

		return cursor + 4, STATUS_OK, trace;

	} else if (mem[cursor] == 2) {		/* multiplication */
		src1   := memread(mem, cursor+1);
		src2   := memread(mem, cursor+2);
		dest   := memread(mem, cursor+3);
		param1 := memread(mem, src1);
		param2 := memread(mem, src2);

		t := fmt.Sprintf("%8s, %8d, %8d, %8d:    mem[%8d] ← %8d * %8d = %8d\n",
			"MULT",
			src1,
			src2,
			dest,
			dest,
			param1,
			param2,
			param1 * param2);
		trace = append(trace, t);

		mem[dest] = param1 * param2;

		return cursor + 4, STATUS_OK, trace;

	} else {				/* unknown opcode */
		t := fmt.Sprintf("ERROR: invalid opcode %d@%d\n", mem[cursor], cursor);
		trace := append(trace, t);
		return 0, STATUS_FAULT, trace;
	}

}

func main() {
	var mem []int64;

	/* iterate over stdin */
	scanner := bufio.NewScanner(os.Stdin);
	for scanner.Scan() {

		/* tokenize each line on "," */
		tokens := strings.Split(scanner.Text(), ",");
		for _, tok := range tokens {

			/* parse each token to an integer, ignoring errors
			 * silently */
			val, _ := strconv.Atoi(tok);

			/* append to the mem slice */
			mem = append(mem, int64(val));


		}
	}

	for noun := 0 ; noun < 100 ; noun ++ {
		for verb := 0 ; verb < 100 ; verb ++ {

			var cursor int64 = 0;
			var status int;

			tempmem := make([]int64, len(mem))
			copy(tempmem, mem)

			tempmem[1] = int64(noun);
			tempmem[2] = int64(verb);

			for true {

				/* execute the next step */
				cursor, status, _ = step(tempmem, cursor);


				/* halt if the status is halt */
				if (status == STATUS_HALT) {
					// memdump(mem);
					break;
				}

				/* error if the status is fault */
				if (status == STATUS_FAULT) {
					// memdump(mem);
					break;
				}
			}

			result := tempmem[0];

			if (status != STATUS_FAULT) {
				fmt.Printf("noun=%8d verb=%8d result=%8d\n",
						noun, verb, result);

				if (result == TARGETVAL) {
					fmt.Printf("TARGETVAL found\n");
					fmt.Printf("ANSWER=%d\n",
						100 * noun + verb);
					os.Exit(0);
				}
			} else {
				fmt.Printf("noun=%8d verb=%8d result=FAULT\n",
						noun, verb);
			}
		}
	}
}


D advent2019/temp.txt => advent2019/temp.txt +0 -1
@@ 1,1 0,0 @@
1969