Skip to content

java: add solutions for year 2016, day 24 #117

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

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

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

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

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

@Benchmark
public void part2() throws IOException {
Day24.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 = "day24",
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,149 @@
package com.github.saser.adventofcode.year2016.day24;

import java.io.BufferedReader;
import java.io.Reader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

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 Day24 {
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 = parse(r);
var keys = findKeys(grid);
var start = findStart(grid, keys);
var distances = findDistances(grid, keys);
var steps = collectKeys(start, keys, distances, part == 2);
return Result.ok(Integer.toString(steps));
}

private static char[][] parse(Reader r) {
return new BufferedReader(r)
.lines()
.map(line -> {
var row = new char[line.length()];
for (var i = 0; i < line.length(); i++) {
row[i] = line.charAt(i);
}
return row;
}).toArray(char[][]::new);
}

private static Point2D findStart(char[][] grid, Set<Point2D> keys) {
for (var key : keys) {
if (grid[key.x][key.y] == '0') {
return key;
}
}
throw new IllegalArgumentException("no start found");
}

private static Set<Point2D> findKeys(char[][] grid) {
var keys = new HashSet<Point2D>();
for (var x = 0; x < grid.length; x++) {
for (var y = 0; y < grid[x].length; y++) {
var c = grid[x][y];
if (c == '#' || c == '.') {
continue;
}
keys.add(new Point2D(x, y));
}
}
return keys;
}

private static Map<Point2D, Map<Point2D, Integer>> findDistances(char[][] grid, Set<Point2D> keys) {
var distances = new HashMap<Point2D, Map<Point2D, Integer>>();
for (var key : keys) {
var queue = new LinkedList<Tuple2<Point2D, Integer>>();
queue.add(new Tuple2<>(key, 0));
var visited = new HashSet<Point2D>();
while (!queue.isEmpty()) {
var tuple = queue.remove();
var point = tuple.v1;
var steps = tuple.v2;
if (visited.contains(point)) {
continue;
}
visited.add(point);
if (keys.contains(point)) {
if (!distances.containsKey(key)) {
distances.put(key, new HashMap<>());
}
distances.get(key).put(point, steps);
if (!distances.containsKey(point)) {
distances.put(point, new HashMap<>());
}
distances.get(point).put(key, steps);
if (distances.get(key).keySet().containsAll(keys)) {
break;
}
}
var neighbors = new Point2D[] {
point.plus(new Point2D(1, 0)),
point.plus(new Point2D(-1, 0)),
point.plus(new Point2D(0, 1)),
point.plus(new Point2D(0, -1)),
};
for (var neighbor : neighbors) {
if (grid[neighbor.x][neighbor.y] == '#') {
continue;
}
queue.add(new Tuple2<>(neighbor, steps + 1));
}
}
}
return distances;
}

private static int collectKeys(Point2D start, Set<Point2D> keys, Map<Point2D, Map<Point2D, Integer>> distances, boolean returnToStart) {
var queue = new PriorityQueue<Tuple3<Point2D, Set<Point2D>, Integer>>(Comparator.comparing(tuple -> tuple.v3));
queue.add(new Tuple3<>(start, Set.of(start), 0));
var visited = new HashSet<Tuple2<Point2D, Set<Point2D>>>();
while (!queue.isEmpty()) {
var tuple = queue.remove();
var point = tuple.v1;
var collected = tuple.v2;
var steps = tuple.v3;
var state = new Tuple2<>(point, collected);
if (visited.contains(state)) {
continue;
}
visited.add(state);
if (collected.containsAll(keys)) {
if (returnToStart) {
steps += distances.get(point).get(start);
}
return steps;
}
for (var entry : distances.get(point).entrySet()) {
var nextKey = entry.getKey();
if (collected.contains(nextKey)) {
continue;
}
var distance = entry.getValue();
var nextCollected = new HashSet<>(collected);
nextCollected.add(nextKey);
var nextSteps = steps + distance;
queue.add(new Tuple3<>(nextKey, nextCollected, nextSteps));
}
}
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.day24.Day24Test",
resources = ["//java/src/test/resources/com/github/saser/adventofcode/year2016/day24:testdata"],
deps = [
"@maven//:junit_junit",
"//java/src/main/java/com/github/saser/adventofcode:adventofcode",
"//java/src/main/java/com/github/saser/adventofcode/year2016/day24:day24",
],
data = ["//inputs:2016/24"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github.saser.adventofcode.year2016.day24;

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

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

public class Day24Test {
@Test
public void part1Example() {
var input = new InputStreamReader(this.getClass().getResourceAsStream("example"));
var output = "14";
var result = Day24.part1(input);
Assert.assertEquals("no error", "", result.error);
Assert.assertEquals("correct output", output, result.answer);
}

@Test
public void part1Actual() throws IOException {
try (var input = new FileReader("inputs/2016/24")) {
var output = "470";
var result = Day24.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/24")) {
var output = "720";
var result = Day24.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,5 @@
###########
#0.1.....2#
#.#######.#
#4.......3#
###########