Browse Source

Pull out intcode vm, add pre-commit hook

master
Chris Smith 4 years ago
parent
commit
f98bac2b64
Signed by: Chris Smith <chris@chameth.com> GPG Key ID: 3A2D4BBDC4A3C9A9
9 changed files with 181 additions and 76 deletions
  1. 7
    7
      .docker/Dockerfile
  2. 20
    0
      .pre-commit-config.yaml
  3. 1
    1
      01/main.go
  4. 13
    22
      02/main.go
  5. 46
    46
      LICENCE.md
  6. 7
    0
      doc.go
  7. 23
    0
      intcode/ops.go
  8. 38
    0
      intcode/vm.go
  9. 26
    0
      intcode/vm_test.go

+ 7
- 7
.docker/Dockerfile View File

@@ -1,7 +1,7 @@
1
-FROM golang:1.13
2
-
3
-ADD entrypoint.sh /entrypoint.sh
4
-RUN chmod +x /entrypoint.sh
5
-
6
-CMD /entrypoint.sh
7
-VOLUME /code
1
+FROM golang:1.13
2
+
3
+ADD entrypoint.sh /entrypoint.sh
4
+RUN chmod +x /entrypoint.sh
5
+
6
+CMD /entrypoint.sh
7
+VOLUME /code

+ 20
- 0
.pre-commit-config.yaml View File

@@ -0,0 +1,20 @@
1
+repos:
2
+  - repo: https://github.com/pre-commit/pre-commit-hooks
3
+    rev: v2.3.0
4
+    hooks:
5
+      - id: check-merge-conflict
6
+      - id: end-of-file-fixer
7
+      - id: trailing-whitespace
8
+  - repo: https://github.com/Lucas-C/pre-commit-hooks
9
+    rev: v1.1.6
10
+    hooks:
11
+      - id: remove-crlf
12
+  - repo: https://github.com/dnephin/pre-commit-golang
13
+    rev: v0.3.4
14
+    hooks:
15
+      - id: go-fmt
16
+      - id: go-vet
17
+      - id: go-build
18
+      - id: go-unit-tests
19
+
20
+exclude: vendor

+ 1
- 1
01/main.go View File

@@ -11,7 +11,7 @@ func fuel(mass int) int {
11 11
 
12 12
 func fuelRequirements(input []int) (int, int) {
13 13
 	var (
14
-		simpleTotal = 0
14
+		simpleTotal    = 0
15 15
 		recursiveTotal = 0
16 16
 	)
17 17
 

+ 13
- 22
02/main.go View File

@@ -3,31 +3,22 @@ package main
3 3
 import (
4 4
 	"fmt"
5 5
 	"github.com/csmith/aoc-2019/common"
6
+	"github.com/csmith/aoc-2019/intcode"
6 7
 	"sync"
7 8
 )
8 9
 
9
-func run(pool sync.Pool, input []int, noun, verb int) int {
10
-	state := pool.Get().([]int)
11
-	defer pool.Put(state)
12
-	copy(state, input)
13
-	state[1] = noun
14
-	state[2] = verb
15
-
16
-	var ip = 0
17
-	for {
18
-		var instr = state[ip]
19
-		if instr == 1 {
20
-			state[state[ip+3]] = state[state[ip+1]] + state[state[ip+2]]
21
-		} else if instr == 2 {
22
-			state[state[ip+3]] = state[state[ip+1]] * state[state[ip+2]]
23
-		} else if instr == 99 {
24
-			return state[0]
25
-		}
26
-		ip += 4
27
-	}
10
+func run(pool *sync.Pool, input []int, noun, verb int) int {
11
+	vm := pool.Get().(*intcode.VirtualMachine)
12
+	defer pool.Put(vm)
13
+
14
+	vm.Reset(input)
15
+	vm.Memory[1] = noun
16
+	vm.Memory[2] = verb
17
+	vm.Run()
18
+	return vm.Memory[0]
28 19
 }
29 20
 
30
-func findOutput(pool sync.Pool, input []int, target int) int {
21
+func findOutput(pool *sync.Pool, input []int, target int) int {
31 22
 	res := make(chan int)
32 23
 
33 24
 	for n := 0; n < 100; n++ {
@@ -46,9 +37,9 @@ func findOutput(pool sync.Pool, input []int, target int) int {
46 37
 func main() {
47 38
 	input := common.Atoi(common.ReadCommas("02/input.txt"))
48 39
 
49
-	pool := sync.Pool{
40
+	pool := &sync.Pool{
50 41
 		New: func() interface{} {
51
-			return make([]int, len(input))
42
+			return intcode.NewVirtualMachine(make([]int, len(input)))
52 43
 		},
53 44
 	}
54 45
 

+ 46
- 46
LICENCE.md View File

@@ -1,46 +1,46 @@
1
-# CC0 1.0 Universal
2
-
3
-```
4
-CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES
5
-NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE
6
-COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND
7
-DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
8
-```
9
-
10
-### Statement of Purpose
11
-
12
-The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
13
-
14
-Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
15
-
16
-For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
17
-
18
-1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
19
-
20
-    i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
21
-
22
-    ii. moral rights retained by the original author(s) and/or performer(s);
23
-
24
-    iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
25
-
26
-    iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
27
-
28
-    v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
29
-
30
-    vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
31
-
32
-    vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
33
-
34
-2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
35
-
36
-3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
37
-
38
-4. __Limitations and Disclaimers.__
39
-
40
-    a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
41
-
42
-    b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
43
-
44
-    c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
45
-
46
-    d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
1
+# CC0 1.0 Universal
2
+
3
+```
4
+CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES
5
+NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE
6
+COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND
7
+DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
8
+```
9
+
10
+### Statement of Purpose
11
+
12
+The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
13
+
14
+Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
15
+
16
+For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
17
+
18
+1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
19
+
20
+    i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
21
+
22
+    ii. moral rights retained by the original author(s) and/or performer(s);
23
+
24
+    iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
25
+
26
+    iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
27
+
28
+    v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
29
+
30
+    vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
31
+
32
+    vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
33
+
34
+2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
35
+
36
+3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
37
+
38
+4. __Limitations and Disclaimers.__
39
+
40
+    a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
41
+
42
+    b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
43
+
44
+    c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
45
+
46
+    d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.

+ 7
- 0
doc.go View File

@@ -0,0 +1,7 @@
1
+package aoc_2019
2
+
3
+// aoc_2019 contains my solutions to Advent of Code 2019.
4
+//
5
+// Each day is contained in a subpackage and can be compiled to its own executable.
6
+//
7
+// There should be no good reason to import this package anywhere.

+ 23
- 0
intcode/ops.go View File

@@ -0,0 +1,23 @@
1
+package intcode
2
+
3
+// OpcodeFunc is a function that describes an opcode implemented in the VM.
4
+type OpcodeFunc = func(vm *VirtualMachine, args []int)
5
+
6
+// AddOpcode takes the values from the memory addresses given by args 1 and 2, adds them together,
7
+// and stores at the memory address given by arg 3.
8
+func AddOpcode(vm *VirtualMachine, args []int) {
9
+	vm.Memory[args[2]] = vm.Memory[args[0]] + vm.Memory[args[1]]
10
+	vm.ip += 4
11
+}
12
+
13
+// MulOpcode takes the values from the memory addresses given by args 1 and 2, muliplies them together,
14
+// and stores at the memory address given by arg 3.
15
+func MulOpcode(vm *VirtualMachine, args []int) {
16
+	vm.Memory[args[2]] = vm.Memory[args[0]] * vm.Memory[args[1]]
17
+	vm.ip += 4
18
+}
19
+
20
+// HaltOpcode halts the VM and takes no arguments.
21
+func HaltOpcode(vm *VirtualMachine, args []int) {
22
+	vm.Halted = true
23
+}

+ 38
- 0
intcode/vm.go View File

@@ -0,0 +1,38 @@
1
+package intcode
2
+
3
+// VirtualMachine is an IntCode virtual machine.
4
+type VirtualMachine struct {
5
+	ip      int
6
+	opcodes map[int]OpcodeFunc
7
+	Memory  []int
8
+	Halted  bool
9
+}
10
+
11
+// NewVirtualMachine creates a new IntCode virtual machine, initialised
12
+// to the given slice of memory.
13
+func NewVirtualMachine(memory []int) *VirtualMachine {
14
+	return &VirtualMachine{
15
+		ip:     0,
16
+		Memory: memory,
17
+		Halted: false,
18
+		opcodes: map[int]OpcodeFunc{
19
+			1:  AddOpcode,
20
+			2:  MulOpcode,
21
+			99: HaltOpcode,
22
+		},
23
+	}
24
+}
25
+
26
+// Run repeatedly executes instructions until the VM halts.
27
+func (vm *VirtualMachine) Run() {
28
+	for !vm.Halted {
29
+		vm.opcodes[vm.Memory[vm.ip]](vm, vm.Memory[vm.ip+1:])
30
+	}
31
+}
32
+
33
+// Reset resets the memory to the given slice, and all other state back to its original value.
34
+func (vm *VirtualMachine) Reset(memory []int) {
35
+	copy(vm.Memory, memory)
36
+	vm.ip = 0
37
+	vm.Halted = false
38
+}

+ 26
- 0
intcode/vm_test.go View File

@@ -0,0 +1,26 @@
1
+package intcode
2
+
3
+import (
4
+	"reflect"
5
+	"testing"
6
+)
7
+
8
+func TestDayTwoSamples(t *testing.T) {
9
+	tables := []struct {
10
+		given    []int
11
+		expected []int
12
+	}{
13
+		{[]int{1, 0, 0, 0, 99}, []int{2, 0, 0, 0, 99}},
14
+		{[]int{2, 3, 0, 3, 99}, []int{2, 3, 0, 6, 99}},
15
+		{[]int{2, 4, 4, 5, 99, 0}, []int{2, 4, 4, 5, 99, 9801}},
16
+		{[]int{1, 1, 1, 4, 99, 5, 6, 0, 99}, []int{30, 1, 1, 4, 2, 5, 6, 0, 99}},
17
+	}
18
+
19
+	for _, table := range tables {
20
+		vm := NewVirtualMachine(table.given)
21
+		vm.Run()
22
+		if !reflect.DeepEqual(table.expected, vm.Memory) {
23
+			t.Errorf("Evaluation of %v was incorrect, got: %v, want: %v.", table.given, vm.Memory, table.expected)
24
+		}
25
+	}
26
+}

Loading…
Cancel
Save