Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 5, 2016 01:25
Show Gist options
  • Save justinAurand/6f2081601db3654df467e15da7605284 to your computer and use it in GitHub Desktop.
Save justinAurand/6f2081601db3654df467e15da7605284 to your computer and use it in GitHub Desktop.
import java.util.function.Predicate;
import java.util.HashMap;
public class DefuseBomb {
private HashMap<Wire, Predicate<Wire>> explosiveWireCutSequences =
new HashMap<Wire, Predicate<Wire>>();
private enum Wire { white, black, purple, red, green, orange };
public DefuseBomb(String[] wireCuts) {
setExplosiveWireCutSequences();
defuseBomb(wireCuts);
}
public static void main(String[] args) {
String[] wireCuts = args;
new DefuseBomb(wireCuts);
}
private boolean areValidWires(String[] wireCuts) {
if (wireCuts == null || wireCuts.length < 1)
return false;
for (String wireCut : wireCuts)
try {
Wire.valueOf(wireCut);
} catch(IllegalArgumentException ex) {
return false;
}
return true;
}
private void defuseBomb(String[] wireCuts) {
if (!areValidWires(wireCuts)) {
System.out.println("Illegal input");
return;
}
if (hasExplosiveSequence(wireCuts))
System.out.println("Boom");
else
System.out.println("Bomb defused");
}
private boolean hasExplosiveSequence(String[] wireCuts) {
for (int i=0; i<wireCuts.length-1; i++) {
Wire wire = Wire.valueOf(wireCuts[i]);
Wire nextWire = Wire.valueOf(wireCuts[i+1]);
if (explosiveWireCutSequences.get(wire).test(nextWire))
return true;
}
return false;
}
private void setExplosiveWireCutSequences() {
explosiveWireCutSequences.put(
Wire.white,
next-> next.equals(Wire.white) ||
next.equals(Wire.black)
);
explosiveWireCutSequences.put(
Wire.black,
next-> next.equals(Wire.white) ||
next.equals(Wire.green) ||
next.equals(Wire.orange)
);
explosiveWireCutSequences.put(
Wire.purple,
next-> next.equals(Wire.white) ||
next.equals(Wire.purple) ||
next.equals(Wire.green) ||
next.equals(Wire.orange)
);
explosiveWireCutSequences.put(
Wire.red,
next-> next.equals(Wire.white) ||
next.equals(Wire.black) ||
next.equals(Wire.purple) ||
next.equals(Wire.red) ||
next.equals(Wire.orange)
);
explosiveWireCutSequences.put(
Wire.green,
next-> next.equals(Wire.black) ||
next.equals(Wire.purple) ||
next.equals(Wire.red) ||
next.equals(Wire.green)
);
explosiveWireCutSequences.put(
Wire.orange,
next-> next.equals(Wire.white) ||
next.equals(Wire.purple) ||
next.equals(Wire.green) ||
next.equals(Wire.orange)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment