Skip to content

java: add solutions for year 2016, day 23 #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
java_library(
name = "benchmark_library",
srcs = glob(["*.java"]),
deps = [
"@maven//:org_openjdk_jmh_jmh_core",
"//java/src/main/java/com/github/saser/adventofcode/year2016/day23:day23",
],
plugins = ["//java/src/benchmark:annotation_processor"],
data = ["//inputs:2016/23"],
)

java_binary(
name = "benchmark",
main_class = "org.openjdk.jmh.Main",
runtime_deps = [
"@maven//:org_openjdk_jmh_jmh_core",
":benchmark_library",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.github.saser.adventofcode.year2016.day23;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;

@BenchmarkMode(Mode.AverageTime)
@Fork(1)
@Measurement(iterations = 1, time = 1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Warmup(iterations = 5, time = 1)
public class Day23Benchmark {
private Reader input;

@Setup
public void setup() throws IOException {
var path = FileSystems.getDefault().getPath("inputs", "2016", "23");
var contents = Files.readString(path);
this.input = new StringReader(contents);
}

@Benchmark
public void part1() throws IOException {
Day23.part1(this.input);
this.input.reset();
}

@Benchmark
public void part2() throws IOException {
Day23.part2(this.input);
this.input.reset();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@
import java.io.BufferedReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.Optional;

public class VM {
public final String[] program;
public final String[][] program;
public int pc;
public Map<String, Integer> registers;
public int[] registers;

public VM(String[] program, int pc, int a, int b, int c, int d) {
this.program = program;
this.program = splitProgram(program);
this.pc = pc;
this.registers = new HashMap<>(Map.of("a", a, "b", b, "c", c, "d", d));
this.registers = new int[] {a, b, c, d};
}

public VM(String[] program) {
Expand All @@ -34,36 +33,42 @@ public static VM from(String program) {
return VM.from(new StringReader(program));
}

private static String[][] splitProgram(String[] program) {
return Arrays.stream(program)
.map(instruction -> instruction.split(" "))
.toArray(String[][]::new);
}

public int a() {
return this.registerValueOf("a").get();
return this.register("a");
}

public int b() {
return this.registerValueOf("b").get();
return this.register("b");
}

public int c() {
return this.registerValueOf("c").get();
return this.register("c");
}

public int d() {
return this.registerValueOf("d").get();
return this.register("d");
}

public void a(int i) {
this.registers.put("a", i);
this.register("a", i);
}

public void b(int i) {
this.registers.put("b", i);
this.register("b", i);
}

public void c(int i) {
this.registers.put("c", i);
this.register("c", i);
}

public void d(int i) {
this.registers.put("d", i);
this.register("d", i);
}

public void runAll() {
Expand All @@ -74,51 +79,82 @@ public void runAll() {

public void run() {
var instruction = this.program[this.pc];
var parts = instruction.split(" ", 2);
var op = parts[0];
var params = parts[1].split(" ");
var op = instruction[0];
var param1 = instruction[1];
var value1 = this.valueOf(param1);
var param2 = Optional.<String>empty();
var value2 = Optional.<Integer>empty();
if (instruction.length - 1 == 2) {
param2 = Optional.of(instruction[2]);
value2 = Optional.of(this.valueOf(param2.get()));
}
var delta = 1;
switch (op) {
case "cpy":
this.registers.put(params[1], valueOf(params[0]));
try {
this.register(param2.get(), value1);
} catch (IllegalArgumentException e) {
// do nothing, this was most likely caused by a `tgl` instruction
}
break;
case "inc":
case "dec":
this.registers.merge(params[0], op.equals("inc") ? 1 : -1, Integer::sum);
try {
this.register(param1, value1 + (op.equals("inc") ? 1 : -1));
} catch (IllegalArgumentException e) {
// do nothing, this was most likely caused by a `tgl` instruction
}
break;
case "jnz":
if (valueOf(params[0]) != 0) {
delta = valueOf(params[1]);
if (value1 != 0) {
delta = value2.get();
}
break;
case "tgl": {
var tglIdx = this.pc + value1;
if (tglIdx >= this.program.length) {
break;
}
var tglOp = this.program[tglIdx][0];
switch (this.program[tglIdx].length - 1) {
case 1: {
this.program[tglIdx][0] = tglOp.equals("inc") ? "dec" : "inc";
break;
}
case 2: {
this.program[tglIdx][0] = tglOp.equals("jnz") ? "cpy" : "jnz";
break;
}
}
break;
}
default:
throw new IllegalArgumentException(String.format("invalid op: %s", op));
}
this.pc += delta;
}

private int valueOf(String x) {
var immediate = this.immediateValueOf(x);
if (immediate.isPresent()) {
return immediate.get();
private int registerOffset(String x) {
var offset = x.charAt(0) - 'a';
if (offset < 0 || offset > 3) {
throw new IllegalArgumentException(String.format("invalid register: %s", x));
}
var register = this.registerValueOf(x);
if (register.isPresent()) {
return register.get();
}
throw new IllegalArgumentException(String.format("invalid parameter: %s", x));
return offset;
}

private int register(String x) {
return this.registers[this.registerOffset(x)];
}

private void register(String x, int i) {
this.registers[this.registerOffset(x)] = i;
}

private Optional<Integer> immediateValueOf(String x) {
private int valueOf(String x) {
try {
var i = Integer.parseInt(x);
return Optional.of(i);
return Integer.parseInt(x);
} catch (NumberFormatException e) {
return Optional.empty();
return this.register(x);
}
}

private Optional<Integer> registerValueOf(String x) {
return Optional.ofNullable(this.registers.get(x));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package(default_visibility = ["//visibility:public"])

java_library(
name = "day23",
srcs = glob(["*.java"]),
deps = ["//java/src/main/java/com/github/saser/adventofcode:adventofcode"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.github.saser.adventofcode.year2016.day23;

import java.io.Reader;

import com.github.saser.adventofcode.Result;

public final class Day23 {
public static Result part1(Reader r) {
return solve(r, 1);
}

public static Result part2(Reader r) {
return solve(r, 2);
}

private static Result solve(Reader r, int part) {
// After studying the code for the program in my input, I found that it
// was calculating the factorial of the initial value of register a,
// plus the product of 75 * 72. This program might not work for all
// inputs, since I assume that the numbers 75 and 72 might be different
// in other outputs; however, I believe the program will perform the
// same calculation.
var result = factorial(part == 1 ? 7 : 12) + 75 * 72;
return Result.ok(Integer.toString(result));
}

private static int factorial(int n) {
int p = 1;
while (n > 1) {
p *= n;
n--;
}
return p;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,12 @@ public void testDay12Example() {
vm.runAll();
Assert.assertEquals(42, vm.a());
}

@Test
public void testDay23Example() {
var r = new InputStreamReader(this.getClass().getResourceAsStream("day23example"));
var vm = VM.from(r);
vm.runAll();
Assert.assertEquals(3, vm.a());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
java_test(
name = "test",
srcs = glob(["*.java"]),
test_class = "com.github.saser.adventofcode.year2016.day23.Day23Test",
deps = [
"@maven//:junit_junit",
"//java/src/main/java/com/github/saser/adventofcode:adventofcode",
"//java/src/main/java/com/github/saser/adventofcode/year2016/day23:day23",
],
data = ["//inputs:2016/23"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.github.saser.adventofcode.year2016.day23;

import java.io.FileReader;
import java.io.IOException;

import org.junit.Test;
import org.junit.Assert;

public class Day23Test {
@Test
public void part1Actual() throws IOException {
try (var input = new FileReader("inputs/2016/23")) {
var output = "10440";
var result = Day23.part1(input);
Assert.assertEquals("no error", "", result.error);
Assert.assertEquals("correct output", output, result.answer);
}
}

@Test
public void part2Actual() throws IOException {
try (var input = new FileReader("inputs/2016/23")) {
var output = "479007000";
var result = Day23.part2(input);
Assert.assertEquals("no error", "", result.error);
Assert.assertEquals("correct output", output, result.answer);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
cpy 2 a
tgl a
tgl a
tgl a
cpy 1 a
dec a
dec a