Skip to content

java: add solutions for year 2016, day 22 #115

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 3 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/day22:day22",
],
plugins = ["//java/src/benchmark:annotation_processor"],
data = ["//inputs:2016/22"],
)

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.day22;

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 Day22Benchmark {
private Reader input;

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

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

@Benchmark
public void part2() throws IOException {
Day22.part2(this.input);
this.input.reset();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package(default_visibility = ["//visibility:public"])

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

import java.io.BufferedReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.github.saser.adventofcode.Result;
import com.github.saser.adventofcode.geo.Point2D;
import com.github.saser.adventofcode.tuple.Tuple2;
import com.github.saser.adventofcode.tuple.Tuple3;

public final class Day22 {
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) {
var grid = Grid.parse(r);
if (part == 1) {
var count = grid.findViable().size();
return Result.ok(Integer.toString(count));
}
var maxX = grid.nodes
.keySet()
.stream()
.mapToInt(point -> point.x)
.max()
.getAsInt();
var from = new Point2D(maxX, 0);
var to = new Point2D(0, 0);
var steps = grid.moveData(from, to);
return Result.ok(Integer.toString(steps));
}

private static class Node {
public final int used;
public final int available;

public Node(int used, int available) {
this.used = used;
this.available = available;
}

public static boolean viable(Node a, Node b) {
if (a.used == 0) {
return false;
}
return a.used <= b.available;
}
}

private static class Grid {
public final Map<Point2D, Node> nodes;

public Grid(Map<Point2D, Node> nodes) {
this.nodes = nodes;
}

public static Grid parse(Reader r) {
var re = Pattern.compile("/dev/grid/node-x(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)%");
var nodes = new HashMap<Point2D, Node>();
var maxX = 0;
var maxY = 0;
var it = new BufferedReader(r)
.lines()
.iterator();
while (it.hasNext()) {
var line = it.next();
var matcher = re.matcher(line);
if (!matcher.matches()) {
continue;
}
var x = Integer.parseInt(matcher.group(1));
maxX = Math.max(maxX, x);
var y = Integer.parseInt(matcher.group(2));
maxY = Math.max(maxY, y);
var point = new Point2D(x, y);
var used = Integer.parseInt(matcher.group(4));
var available = Integer.parseInt(matcher.group(5));
nodes.put(point, new Node(used, available));
}
return new Grid(nodes);
}

private Point2D findEmpty() {
return this.nodes
.entrySet()
.stream()
.filter(entry -> entry.getValue().used == 0)
.map(Map.Entry::getKey)
.findFirst()
.get();
}

public Set<Point2D> findViable() {
var empty = this.findEmpty();
var emptyNode = this.nodes.get(empty);
return this.nodes
.entrySet()
.stream()
.filter(entry -> !entry.getKey().equals(empty))
.filter(entry -> Node.viable(entry.getValue(), emptyNode))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}

public int moveData(Point2D from, Point2D to) {
var queue = new LinkedList<Tuple3<Point2D, Point2D, Integer>>();
var empty = this.findEmpty();
queue.add(new Tuple3<>(empty, from.clone(), 0));
var visited = new HashSet<Tuple2<Point2D, Point2D>>();
var maxX = 0;
var maxY = 0;
for (var point : this.nodes.keySet()) {
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
}
var viable = this.findViable();
viable.add(empty);
while (!queue.isEmpty()) {
var tuple = queue.remove();
var emptyPosition = tuple.v1;
var dataPosition = tuple.v2;
var state = new Tuple2<>(emptyPosition, dataPosition);
if (visited.contains(state)) {
continue;
}
visited.add(state);
var steps = tuple.v3;
if (dataPosition.equals(to)) {
return steps;
}
var neighbors = new Point2D[] {
emptyPosition.plus(new Point2D(1, 0)),
emptyPosition.plus(new Point2D(-1, 0)),
emptyPosition.plus(new Point2D(0, 1)),
emptyPosition.plus(new Point2D(0, -1)),
};
for (var neighbor : neighbors) {
var nx = neighbor.x;
var ny = neighbor.y;
if (nx < 0 || nx > maxX || ny < 0 || ny > maxY) {
continue;
}
if (!viable.contains(neighbor)) {
continue;
}
var newDataPosition = (neighbor.equals(dataPosition) ? emptyPosition : dataPosition).clone();
queue.add(new Tuple3<>(neighbor, newDataPosition, steps + 1));
}
}
return -1;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
java_test(
name = "test",
srcs = glob(["*.java"]),
test_class = "com.github.saser.adventofcode.year2016.day22.Day22Test",
resources = ["//java/src/test/resources/com/github/saser/adventofcode/year2016/day22:testdata"],
deps = [
"@maven//:junit_junit",
"//java/src/main/java/com/github/saser/adventofcode:adventofcode",
"//java/src/main/java/com/github/saser/adventofcode/year2016/day22:day22",
],
data = ["//inputs:2016/22"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github.saser.adventofcode.year2016.day22;

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

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

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

@Test
public void part2Example() {
var input = new InputStreamReader(this.getClass().getResourceAsStream("example"));
var output = "7";
var result = Day22.part2(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/22")) {
var output = "236";
var result = Day22.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 @@
package(default_visibility = ["//visibility:public"])

filegroup(
name = "testdata",
testonly = 1,
srcs = glob(["*"]),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Filesystem Size Used Avail Use%
/dev/grid/node-x0-y0 10T 8T 2T 80%
/dev/grid/node-x0-y1 11T 6T 5T 54%
/dev/grid/node-x0-y2 32T 28T 4T 87%
/dev/grid/node-x1-y0 9T 7T 2T 77%
/dev/grid/node-x1-y1 8T 0T 8T 0%
/dev/grid/node-x1-y2 11T 7T 4T 63%
/dev/grid/node-x2-y0 10T 6T 4T 60%
/dev/grid/node-x2-y1 9T 8T 1T 88%
/dev/grid/node-x2-y2 9T 6T 3T 66%