Skip to content

Instantly share code, notes, and snippets.

@sanity
Created June 9, 2011 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanity/1017292 to your computer and use it in GitHub Desktop.
Save sanity/1017292 to your computer and use it in GitHub Desktop.
private void simplify(final GPCandidateProgram p) {
final String oldString = p.toString();
if (!p.isValid())
return;
p.setRootNode(simplify(p.getRootNode()));
final String newString = p.toString();
}
private Node simplify(Node node) {
for (int childIX = 0; childIX < node.getChildren().length; childIX++) {
final Node oldChild = node.getChildren()[childIX];
node.setChild(childIX, simplify(oldChild));
}
// Literal compression
final Set<Class<?>> eligibleForLiteralCompression = Sets.<Class<?>> newHashSet(
AddFunction.class,
SubtractFunction.class, MultiplyFunction.class, DivisionProtectedFunction.class,
GreaterThanFunction.class, Min2Function.class, Max2Function.class, AndFunction.class, OrFunction.class,
NotFunction.class);
if (eligibleForLiteralCompression.contains(node.getClass())) {
boolean allChildrenAreLiteral = true;
for (final Node child : node.getChildren()) {
if (!(child instanceof Literal)) {
allChildrenAreLiteral = false;
break;
}
}
if (allChildrenAreLiteral) {
final Object evaluate = node.evaluate();
node = new Literal(evaluate);
}
}
// If compression
if (node instanceof IfFunction) {
if (node.getChild(0) instanceof Literal) {
if (((Literal) (node.getChild(0))).getValue().equals(true)) {
node = node.getChild(1);
} else {
node = node.getChild(2);
}
} else if (node.getChild(1).equals(node.getChild(2))) {
node = node.getChild(1);
}
}
// Or compression
if (node instanceof OrFunction) {
if (node.getChild(0) instanceof Literal) {
if (((Literal) node.getChild(0)).getValue().equals(false)) {
node = node.getChild(1);
} else {
node = new Literal(true);
}
} else if (node.getChild(1) instanceof Literal) {
if (((Literal) node.getChild(1)).getValue().equals(false)) {
node = node.getChild(0);
} else {
node = new Literal(true);
}
} else if (node.getChild(0).equals(node.getChild(1))) {
node = node.getChild(0);
}
}
// And compression
if (node instanceof AndFunction) {
if (node.getChild(0) instanceof Literal) {
if (((Literal) node.getChild(0)).getValue().equals(true)) {
node = node.getChild(1);
} else {
node = new Literal(false);
}
} else if (node.getChild(1) instanceof Literal) {
if (((Literal) node.getChild(1)).getValue().equals(true)) {
node = node.getChild(0);
} else {
node = new Literal(false);
}
} else if (node.getChild(0).equals(node.getChild(1))) {
node = node.getChild(0);
}
}
// Double-not
if (node instanceof NotFunction) {
if (node.getChild(0) instanceof NotFunction) {
node = node.getChild(0).getChild(0);
}
}
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment