001    /*
002     * Created on Sep 8, 2004
003     *
004     */
005    package aima.search.framework;
006    
007    import java.util.ArrayList;
008    import java.util.List;
009    
010    /**
011     * @author Ravi Mohan
012     * 
013     */
014    
015    public abstract class QueueSearch extends NodeExpander {
016            private static String QUEUE_SIZE = "queueSize";
017    
018            private static String MAX_QUEUE_SIZE = "maxQueueSize";
019    
020            private static String PATH_COST = "pathCost";
021    
022            public List<String> search(Problem problem, NodeStore fringe) {
023                    clearInstrumentation();
024                    fringe.add(new Node(problem.getInitialState()));
025                    setQueueSize(fringe.size());
026                    while (!(fringe.isEmpty())) {
027                            Node node = fringe.remove();
028                            setQueueSize(fringe.size());
029                            if (problem.isGoalState(node.getState())) {
030                                    setPathCost(node.getPathCost());
031                                    return SearchUtils.actionsFromNodes(node.getPathFromRoot());
032                            }
033                            addExpandedNodesToFringe(fringe, node, problem);
034                            setQueueSize(fringe.size());
035                    }
036                    return new ArrayList<String>();// Empty List indicates Failure
037            }
038    
039            @Override
040            public void clearInstrumentation() {
041                    super.clearInstrumentation();
042                    metrics.set(QUEUE_SIZE, 0);
043                    metrics.set(MAX_QUEUE_SIZE, 0);
044                    metrics.set(PATH_COST, 0);
045            }
046    
047            public int getQueueSize() {
048                    return metrics.getInt("queueSize");
049            }
050    
051            public void setQueueSize(int queueSize) {
052    
053                    metrics.set(QUEUE_SIZE, queueSize);
054                    int maxQSize = metrics.getInt(MAX_QUEUE_SIZE);
055                    if (queueSize > maxQSize) {
056                            metrics.set(MAX_QUEUE_SIZE, queueSize);
057                    }
058            }
059    
060            public int getMaxQueueSize() {
061                    return metrics.getInt(MAX_QUEUE_SIZE);
062            }
063    
064            public double getPathCost() {
065                    return metrics.getDouble(PATH_COST);
066            }
067    
068            public void setPathCost(Double pathCost) {
069                    metrics.set(PATH_COST, pathCost);
070            }
071    
072            public abstract void addExpandedNodesToFringe(NodeStore fringe, Node node,
073                            Problem p);
074    }