Пример #1
0
        public void Step()
        {
            if (IsFinished)
            {
                return;
            }

            SearchNode <TState, TAction> node;

            do
            {
                if (Frontier.IsEmpty())
                {
                    IsFinished = true;
                    return;
                }
                node = Frontier.Pop();
            } while (_explored.ContainsKey(node.State));

            _explored[node.State] = node;
            CurrentState          = node.State;
            var actions = _problem.GetActions(node.State);

            foreach (var action in actions)
            {
                var childState = _problem.DoAction(node.State, action);
                var childCost  = node.PathCost + _problem.PathCost(node.State, action);
                var child      = new SearchNode <TState, TAction>(childState, node, action, childCost);

                if (_explored.ContainsKey(childState) || Frontier.ContainsState(childState))
                {
                    continue;
                }

                if (_problem.IsGoal(childState))
                {
                    CurrentState = childState;
                    IsFinished   = true;
                    IsSolved     = true;
                    // add goal to explored to allow this.getSolutionTo(goal)
                    _explored[childState] = child;
                }
                else
                {
                    Frontier.Push(child);
                }
            }
        }
Пример #2
0
        public void Step_ShouldGoToBetterState()
        {
            var state3 = new StateMock("3");
            var state2 = new StateMock("2");
            var state1 = new StateMock("1");

            var action1 = new ActionMock("1");
            var action3 = new ActionMock("3");

            A.CallTo(() => _problem.InitialState).Returns(state2);
            A.CallTo(() => _problem.GetActions(state2)).Returns(new[] { action1, action3 });
            A.CallTo(() => _problem.DoAction(state2, action1)).Returns(state1);
            A.CallTo(() => _problem.DoAction(state2, action3)).Returns(state3);

            var search = new AStarSearch <StateMock, ActionMock>(_problem, state => int.Parse(state.Value));

            // act
            search.Step(); // step 1 sets current state to initial state
            search.Step();

            // assert
            Assert.AreEqual(state1, search.CurrentState);
        }