Skip to content

Instantly share code, notes, and snippets.

@almendar
Created December 14, 2021 19:06
Show Gist options
  • Save almendar/a0fa9f5f9078c1a6501f7d5ec7977e1f to your computer and use it in GitHub Desktop.
Save almendar/a0fa9f5f9078c1a6501f7d5ec7977e1f to your computer and use it in GitHub Desktop.
package day12;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
public class Day12 {
public Day12() {
this.t = new HashMap<>();
}
private HashMap<String, ArrayList<String>> t;
void add(String from, String to) {
if (!from.equals("end") && !to.equals("start")) {
var currentList = t.get(from);
if (currentList == null) {
currentList = new ArrayList<>();
}
currentList.add(to);
t.put(from, currentList);
}
}
public void readInput(String input) throws IOException {
var lines = Files.readString(Paths.get(input)).split("\n");
for (int i = 0; i < lines.length; i++) {
var line = lines[i];
var tmp = line.split("-");
add(tmp[0], tmp[1]);
add(tmp[1], tmp[0]);
}
}
public void prettyPrint() {
for (var key : t.keySet()) {
var line = t.get(key);
System.out.print(key + ": ");
line.stream().forEach(s -> System.out.print(s + " "));
System.out.println();
}
}
boolean lowerCaseMaxTwice(String item, ArrayList<String> path) {
var counts = new HashMap<String, Integer>();
var wasTwice = false;
for (var v : path) {
if (v.equals(v.toLowerCase())) {
var count = counts.getOrDefault(v, 0);
count += 1;
counts.put(v, count);
if (count.equals(2)) {
wasTwice = true;
}
}
}
if (wasTwice) {
return counts.getOrDefault(item, 0).equals(0);
} else {
return counts.getOrDefault(item, 0) < 2;
}
}
public int step(String node, ArrayList<String> path) {
var count = 0;
var moves = t.get(node);
for (var v : moves) {
if (!lowerCaseMaxTwice(v, path)) {
continue;
}
if (v.equals("end")) {
count += 1;
} else {
var pathHere = new ArrayList<>(path);
pathHere.add(v);
count += step(v, pathHere);
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment