net.amygdalum.patternsearchalgorithms.automaton.chars.StateClone Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of patternsearchalgorithms Show documentation
Show all versions of patternsearchalgorithms Show documentation
Searching and Matching Regular Expressions
package net.amygdalum.patternsearchalgorithms.automaton.chars;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Queue;
import net.amygdalum.util.tuples.Pair;
import net.amygdalum.util.worklist.WorkSet;
public class StateClone {
private State start;
private IdentityHashMap states;
public StateClone(State start) {
this.start = start;
this.states = new IdentityHashMap();
}
public static StateClone cloneTree(State start) {
StateClone stateClone = new StateClone(start);
stateClone.process();
return stateClone;
}
private void process() {
Queue> workset = new WorkSet<>();
State clonedStart = start.asPrototype();
workset.add(new Pair<>(start, clonedStart));
states.put(start, clonedStart);
while (!workset.isEmpty()) {
Pair current = workset.remove();
State state = current.left;
State cloned = current.right;
List> next = transferState(state, cloned);
workset.addAll(next);
}
}
private List> transferState(State state, State cloned) {
List> next = new ArrayList<>();
if (state.isAccepting()) {
cloned.setAccepting();
}
if (state.isSilent()) {
cloned.setSilent();
}
for (Transition transition : state.out()) {
State target = transition.getTarget();
State clonedtarget = states.get(target);
if (clonedtarget == null) {
clonedtarget = target.asPrototype();
states.put(target, clonedtarget);
next.add(new Pair<>(target, clonedtarget));
}
Transition clonedtransition = transition.asPrototype().withOrigin(cloned).withTarget(clonedtarget);
clonedtransition.connect();
}
return next;
}
public State get(State state) {
return states.get(state);
}
public State getStart() {
return states.get(start);
}
}