Skip to content

Instantly share code, notes, and snippets.

@zain
Created December 2, 2019 15:30
Show Gist options
  • Save zain/3b34573d8c69ddb29d9159ae77931a42 to your computer and use it in GitHub Desktop.
Save zain/3b34573d8c69ddb29d9159ae77931a42 to your computer and use it in GitHub Desktop.
AoC 2019 day 2
package main
import (
"fmt"
"io/ioutil"
"log"
"strconv"
"strings"
)
func main() {
b := readFile("day2")
strProgram := strings.Split(string(b), ",")
program := make([]int, len(strProgram))
for i, s := range strProgram {
program[i] = toInt(s)
}
// part 1
program[1] = 12
program[2] = 2
output := runIntcode(program)
fmt.Println(output[0])
// part 2
for i := 0; i < 100; i++ {
for j := 0; j < 100; j++ {
program[1] = i
program[2] = j
output := runIntcode(program)
if output[0] == 19690720 {
fmt.Println(i, "and", j, "=>", 100*i+j)
}
}
}
}
func runIntcode(programOrig []int) []int {
program := make([]int, len(programOrig))
copy(program, programOrig)
cursor := 0
for {
opcode := program[cursor]
switch opcode {
case 1:
i1Pos := program[cursor+1]
i2Pos := program[cursor+2]
outputPos := program[cursor+3]
program[outputPos] = program[i1Pos] + program[i2Pos]
case 2:
i1Pos := program[cursor+1]
i2Pos := program[cursor+2]
outputPos := program[cursor+3]
program[outputPos] = program[i1Pos] * program[i2Pos]
case 99:
return program
default:
log.Fatal("Received bad opcode: ", opcode)
}
cursor += 4
}
}
func readFile(filename string) string {
bytes, err := ioutil.ReadFile(filename)
check(err)
return strings.TrimSpace(string(bytes))
}
func toInt(s string) int {
result, err := strconv.Atoi(s)
check(err)
return result
}
func check(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment