Skip to content

Instantly share code, notes, and snippets.

@desrtfx
Created December 19, 2015 15:25
Show Gist options
  • Save desrtfx/eab96fd43675c9853bd7 to your computer and use it in GitHub Desktop.
Save desrtfx/eab96fd43675c9853bd7 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Day19v2 {
public static String replace(String where, String what, String with, int pos) {
return where.substring(0, pos) + with + where.substring(pos + what.length());
}
public static void main(String[] args) {
List<String[]> transforms = FileIO.getFileLinesSplit(".\\InputDay19.txt", " => ");
String medicine = "ORnPBPMgArCaCaCaSiThCaCaSiThCaCaPBSiRnFArRnFArCaCaSiThCaCaSiThCaCaCaCaCaCaSiRnFYFArSiRnMgArCaSiRnPTiTiBFYPBFArSiRnCaSiRnTiRnFArSiAlArPTiBPTiRnCaSiAlArCaPTiTiBPMgYFArPTiRnFArSiRnCaCaFArRnCaFArCaSiRnSiRnMgArFYCaSiRnMgArCaCaSiThPRnFArPBCaSiRnMgArCaCaSiThCaSiRnTiMgArFArSiThSiThCaCaSiRnMgArCaCaSiRnFArTiBPTiRnCaSiAlArCaPTiRnFArPBPBCaCaSiThCaPBSiThPRnFArSiThCaSiThCaSiThCaPTiBSiRnFYFArCaCaPRnFArPBCaCaPBSiRnTiRnFArCaPRnFArSiRnCaCaCaSiThCaRnCaFArYCaSiRnFArBCaCaCaSiThFArPBFArCaSiRnFArRnCaCaCaFArSiRnFArTiRnPMgArF";
// part 1
List<String> molecules = new ArrayList<>();
for (String[] trans : transforms) {
int pos = 0;
while ((pos = medicine.indexOf(trans[0], pos)) >= 0) {
molecules.add(replace(medicine, trans[0], trans[1], pos));
pos += trans[0].length();
}
}
long count = molecules.stream().distinct().count();
System.out.println("Part 1: Total unique molecules = " + count);
// part 2
Collections.shuffle(transforms);
int count2 = 0;
int reshuffleCount = 0;
String tmp = new String(medicine);
while (!tmp.equals("e")) {
String last = tmp;
for (String[] trans : transforms) {
if (tmp.contains(trans[1])) {
tmp = replace(tmp, trans[1], trans[0], tmp.indexOf(trans[1]));
// System.out.println(medicine);
count2++;
}
}
if (last.equals(tmp) && (!tmp.equals("e"))) {
Collections.shuffle(transforms);
tmp = new String(medicine);
count2 = 0;
reshuffleCount++;
}
}
System.out.println("Part 2: Transforms taken = " + count2 + " Reshuffled " + reshuffleCount + " times.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment