// Use this for initialization void Start() { Graph g = new Graph(); for (int i = 1; i < 6; i++) { g.AddNode(i); } g.AddEdge(1, 2); g.AddEdge(1, 3); g.AddEdge(2, 4, 7); g.AddEdge(4, 5); g.AddEdge(3, 5, 5f); List <GraphEdge> path; GraphSearch.Dijkstra(g, g.GetNode(1), g.GetNode(5), out path); float cost = 0; foreach (GraphEdge e in path) { Debug.Log(e.from.index + " - " + e.to.index); cost += e.cost; } Debug.Log("Total Cost: " + cost); }
public void trim() { GraphSearch.fromPosition(Size_x / 2, Size_y / 2) .DepthFirstFlood(Map_data_passable, GraphSearch.DefaultPassable, new ActionOnVisit(MarkOneAsTwo)); for (int i = 0; i < Size_x; i++) { for (int j = 0; j < Size_y; j++) { if (Map_data_passable[i, j] == 1) { Map_data_passable[i, j] = 0; } } } for (int i = 0; i < Size_x; i++) { for (int j = 0; j < Size_y; j++) { if (Map_data_passable[i, j] == 2) { Map_data_passable[i, j] = 1; } } } }
public GraphCycleEdgeVisitor(GraphSearch <V, E> search) { parent = new Dictionary <IVertex <V>, IVertex <V> >(); Search = search; HasCycle = false; }
public override int Compare(Unit x, Unit y) { return((int)((GraphSearch.fromPosition(x.Map_position_x, x.Map_position_y) .manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y) - GraphSearch.fromPosition(y.Map_position_x, y.Map_position_y) .manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y)) * 100.0f)); }
private void MoveDroidToSecurityCheckpoint(Droid droid, ShipGraph shipGraph) { var(path, _) = GraphSearch.Dijkstra(shipGraph, droid.Room, "== Security Checkpoint =="); foreach (var nextRoom in path) { droid.TakeDoor((Direction)shipGraph.GetDoorDirection(droid.Room, nextRoom)); } }
public List <VacancyPersonApplication> ConsultVacancyApplications(int vacancyId) { Vacancy vacancyInfo = _vacanciesRepository.VacancyConsult(vacancyId); List <VacancyPersonApplication> applications = _applicationsRepository.ConsultApplications(vacancyId); Graph graph = new Graph(); var search = new GraphSearch(); graph.AddPoint("A"); graph.AddPoint("B"); graph.AddPoint("C"); graph.AddPoint("D"); graph.AddPoint("E"); graph.AddPoint("F"); graph.AddConnection("A", "B", 5); graph.AddConnection("B", "C", 7); graph.AddConnection("B", "D", 3); graph.AddConnection("C", "E", 4); graph.AddConnection("D", "E", 10); graph.AddConnection("D", "F", 8); var Alldistances = search.FindAllRouteFromTheStart(graph, vacancyInfo.Location); foreach (VacancyPersonApplication vacancyPersonApplication in applications) { double distance = Alldistances[vacancyPersonApplication.Location]; int N = 100 - 25 * (vacancyInfo.Level - vacancyPersonApplication.Level); int D = 0; if (distance <= 20 && distance > 15) { D = 25; } else if (distance <= 15 && distance > 10) { D = 50; } else if (distance <= 10 && distance > 5) { D = 75; } else if (distance <= 5 && distance >= 0) { D = 100; } vacancyPersonApplication.Score = (N + D) / 2; } return(applications.OrderByDescending(i => i.Score).ToList()); }
bool transitionInAttackRange() { return(GraphSearch .fromPosition(unit.Map_position_x, unit.Map_position_y) .manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y) <= unit.MainSpell.CastRange || GraphSearch .fromPosition(unit.Map_position_x, unit.Map_position_y) .manhattanDistanceFromTarget(GameTools.Base.Map_position_x, GameTools.Base.Map_position_y) <= unit.MainSpell.CastRange); }
public static GraphSearch fromPosition(int x1, int y1) { if (instance == null) { instance = new GraphSearch(); } x = x1; y = y1; return(instance); }
public void BreadthFirstSearchTest() { //Arrange var graph = new Graph <int>(vertices, edges); var search = new GraphSearch(); //Act string result = new StringBuilder(string.Join(", ", search.BreadthFirstSearch(graph, 1))).ToString(); // Assert Assert.Equal("1, 2, 3, 4, 5, 6, 7, 8, 9, 10", result); }
private GraphSearch BuildSearch(IEnumerable <TrustModel> trusts) { var graphService = new GraphContext(); var builder = new GraphBuilder(graphService); builder.Build(trusts); var search = new GraphSearch(graphService); return(search); }
private void ButtonSolveClick(object sender, RoutedEventArgs e) { if (_currentPolyLine.Points.Count >= 2) { _currentPolyLine.Points.Add(_currentPolyLine.Points[0]); } var initialState = new PathFindingState(new Search.Types.Point(100, 100)); var goalState = new PathFindingState(new Search.Types.Point(800, 600)); var environment = new PathFindingEnvironment(); foreach (var polyLine in _polyLines) { var points = polyLine.Points.Select(p => p).Distinct().ToList(); for (int i = 0; i < points.Count; i++) { for (int j = i + 1; j < points.Count; j++) { if (i == j) { continue; } var pointLine = new PointLine( new Point(points[i].X, points[i].Y), new Point(points[j].X, points[j].Y)); environment.PointLines.Add(pointLine); } } } var actionFunction = new PathFindingActionFunction(environment, goalState); var resultFunction = new PathFindingResultFunction(); var goalTest = new PathFindingGoalTest(goalState); var stepCost = new PathFindingStepCost(); var searchAlgorithm = new GraphSearch <PathFindingState, PathFindingAction>(); var problem = new Problem <PathFindingState, PathFindingAction>(initialState, actionFunction, resultFunction, goalTest, stepCost); var solution = searchAlgorithm.Search(problem); for (int i = 1; i < solution.Count; i++) { AddLine( solution[i - 1].State.Point.X, solution[i - 1].State.Point.Y, solution[i].State.Point.X, solution[i].State.Point.Y); } }
public void ShortestPath() { //Arrange var graph = new Graph <int>(vertices, edges); var search = new GraphSearch(); //Act var result = search.ShortestPath(graph, 1); string shortestPath = string.Empty; // Assert shortestPath = (string.Join(", ", result(7))); Assert.Equal("1, 2, 4, 7", shortestPath); }
public void FindAttackRange() { GraphSearch mSearch = new GraphSearch(mTileMap.MapInfo.mGraph); mSearch.AttackRange(mPositionX, mPositionY, mRange); mAttackRangeList = mSearch.GetCloseList(); //int positionIndex = mTileMap.MapInfo.XYToIndex (mPositionX, mPositionY); mAttackRangeList.RemoveAt(0); foreach (Node i in mAttackRangeList) { int index = i.mIndex; DTileMap.TileType temp = mTileMap.MapInfo.GetTileTypeIndex(index); if (temp == DTileMap.TileType.Player1) { mAttackList.Add(DTileMap.TileType.Player1); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Player2) { mAttackList.Add(DTileMap.TileType.Player2); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Player3) { mAttackList.Add(DTileMap.TileType.Player3); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Player4) { mAttackList.Add(DTileMap.TileType.Player4); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Target1) { mAttackList.Add(DTileMap.TileType.Target1); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Target2) { mAttackList.Add(DTileMap.TileType.Target2); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } else if (temp == DTileMap.TileType.Target3) { mAttackList.Add(DTileMap.TileType.Target3); mAttackPosition.Add(mTileMap.MapInfo.GetTileLocationIndex(index)); } } }
public void GraphSearchPerformanceTest() { int graphSize = 1024; int iteration = 100; float density = 0.5f; PathGrid graph = new PathGrid(0, 0, graphSize, graphSize, graphSize, graphSize); var picks = new int[graphSize * graphSize]; for (int i = 0; i < picks.Length; ++i) { picks[i] = i; } Random random = new Random(0); int obstacleCount = (int)(density * graphSize * graphSize); while (obstacleCount > 0) { var i = random.Next(obstacleCount); graph.Mark(picks[i] % graphSize, picks[i] / graphSize); obstacleCount--; picks[i] = picks[obstacleCount]; } int walkables = picks.Length - obstacleCount; GraphSearch search = new GraphSearch(); List <int> result = new List <int>(); int[] array = new int[graphSize * graphSize]; GC.Collect(); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < iteration; ++i) { result.Clear(); search.Search(graph, picks[random.Next(walkables)], picks[random.Next(walkables)], result); } watch.Stop(); Trace.WriteLine("Max searches per frame (60 FPS): " + iteration / watch.Elapsed.TotalSeconds / 60.0); }
public void solveLab(string algorithm) { FrameWork myProblem = new FrameWork(colorsMatrixNormalized, Int32.Parse(nSize.text)); foreach (var element in myProblem.initialStates) { Debug.Log(element[0] + ", " + element[1] + " 2"); } GraphSearch graph = new GraphSearch(myProblem, 1); List <int[]> path = graph.JustDoIt(); foreach (var element in path) { Debug.Log(element[0] + ", " + element[1]); } }
private static void TestBfsDirectedSmallGraph(string path) { IDirectedGraph <int> graph = null; using (var reader = new StreamReader(path)) { graph = GraphHelper.ParseFromTextDirectedGraph(reader, saveReversedVersion: false); Console.WriteLine("Graph initiated!"); Console.WriteLine(graph); } foreach (int exploredNode in GraphSearch.BreadthFirst(graph, 1)) { Console.WriteLine(exploredNode); } }
protected override void InitMapPosition() { if (Map_position_x == 0 && Map_position_y == 0) { Map_position_x = Random.Range(0, GameTools.Map.size_x); Map_position_y = Random.Range(0, GameTools.Map.size_z); while (GameTools.Map.map_unit_occupy[Map_position_x, Map_position_y] != null || (!TileTools.IsLand(GameTools.Map.TileMapData[Map_position_x, Map_position_y])) || GraphSearch.fromPosition(Map_position_x, Map_position_y).manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y) < 10) { Map_position_x = Random.Range(0, GameTools.Map.size_x); Map_position_y = Random.Range(0, GameTools.Map.size_z); } } }
private static void TestShortestPath(string path) { IDirectedGraph <int> graph = null; using (var reader = new StreamReader(path)) { graph = GraphHelper.ParseFromTextDirectedGraph(reader, saveReversedVersion: false); Console.WriteLine("Graph initiated!"); Console.WriteLine(graph); } int startVertex = 1, endVertex = 9; var shortestPath = GraphSearch.ComputeShortestPath(graph, startVertex, endVertex); Console.WriteLine($"Shortest path in graph from vertex {startVertex} to {endVertex} is {shortestPath}"); }
private static List <int> TestDijkstraSearch(string path) { IDirectedWeightedGraph <int> graph; using (var reader = new StreamReader(path)) { graph = GraphHelper.ParseFromTextDirectedWeightedGraph(reader); } int[] result = GraphSearch.DijkstraMinHeap(graph, 1); int[] requiredPaths = { 7, 37, 59, 82, 99, 115, 133, 165, 188, 197 }; return(requiredPaths.Select(i => result[i]) .ToList()); }
public void GreedyGraphSearch() { // Arrange var problem = new TriForkTestProblem(); var search = new GraphSearch<TestState>(new GreedySearchFringe<TestState>(new TestStateHuristic()), new TestStateEqualityComparer()); // Act var result = search.Execute(problem); // Assert var expanded = problem.Expanded.Select(s => s.Node.Name); var resultPath = result.Path.Select(n => n.Name); Assert.Equal(new[] { "Start", "B" }, expanded); Assert.Equal(new[] { "Start", "B", "Goal" }, resultPath); }
public int GetDistance(string from, string to) { if (!distanceMatrix.TryGetValue(from, out var nextDict)) { distanceMatrix[from] = new Dictionary <string, int>(); } if (!distanceMatrix[from].TryGetValue(to, out var distance)) { var(_, dist) = GraphSearch.Dijkstra(this, from, to); distanceMatrix[from][to] = dist; return(dist); } else { return(distance); } }
public string Solve() { var graph = GetDirectedGraphFromSccInput(); var componentsSizes = new List <int>(); var searcher = new GraphSearch(InputMaxNodeNumber); var connectedComponents = searcher.KasarajuFindSccs(graph); foreach (var component in connectedComponents) { componentsSizes.Add(component.Count); } componentsSizes.Sort(); componentsSizes.Reverse(); var topFiveComponents = componentsSizes.Take(5).ToArray(); return(string.Join(", ", topFiveComponents)); }
public void FindWalkRange(int movement) { GraphSearch mSearch = new GraphSearch(mTileMap.MapInfo.mGraph); mSearch.RangeSearch(mPositionX, mPositionY, movement); mWalkRangeList = mSearch.GetCloseList(); foreach (Node i in mWalkRangeList) { int index = i.mIndex; DTileMap.TileType temp = mTileMap.MapInfo.GetTileTypeIndex(index); if (temp == DTileMap.TileType.Floor) { mTileMap.MapInfo.SetTileTypeIndex(index, DTileMap.TileType.Walkable, true); } if (temp == DTileMap.TileType.Sewer) { mTileMap.MapInfo.SetTileTypeIndex(index, DTileMap.TileType.TrueSewer, true); } } }
private static void TestFindStronglyConnectedComponents(string path) { IDirectedGraphWithReversed <int> graph; using (var reader = new StreamReader(path)) { graph = GraphHelper.ParseFromTextDirectedGraph(reader, saveReversedVersion: true); } var results = GraphSearch.FindStronglyConnectedComponents(graph); var biggestSccs = results.OrderByDescending(r => r.Count) .Take(6) .ToList(); Console.WriteLine($"Strongly connected components number - {biggestSccs.Count}!"); for (var i = 0; i < biggestSccs.Count; i++) { var sccVertices = biggestSccs[i]; Console.WriteLine($"SCC #{i+1}: {sccVertices.Count}"); } }
private static void TestDfs(string path) { IDirectedGraph <int> graph = null; using (var reader = new StreamReader(path)) { graph = GraphHelper.ParseFromTextDirectedGraph(reader, saveReversedVersion: false); Console.WriteLine("Graph initiated!"); Console.WriteLine(graph); } int startVertex = 1; Console.WriteLine($"Dfs result. Start vertex - {startVertex}"); var result = GraphSearch.DepthFirst(graph, 1); foreach (int node in result) { Console.WriteLine(node); } }
//Path Find Parts List <Node> PathFind(int startX, int startY, int endX, int endY) { List <Node> Path = null; GraphSearch mSearch = new GraphSearch(mTileMap.MapInfo.mGraph); mSearch.PathFind(startX, startY, endX, endY); if (mSearch.IsFound()) { //mCloseList = mSearch.GetCloseList(); Path = mSearch.GetPathList(); //foreach(Node i in Path) //{ // mTileMap.MapInfo.SetTileTypeIndex(i.mIndex,DTileMap.TileType.Path); //} } else { Debug.Log("No Path is found"); } return(Path); }
static void Main(string[] args) { var people = new PeopleCollection(); new GedcomImport().Import(people, @"C:\Users\davit\source\repos\RelationshipSearch\hayden.ged"); Person from = people[0]; Person to = people[163]; var solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonChildState(from), new GoalTest(to)); if (solution == null) { solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonParentState(from), new GoalTest(to)); } if (solution == null) { solution = new GraphSearch(new BreadthFirstFrontier()).FindSolution(new PersonCousinState(from, true), new GoalTest(to)); } var html = HtmlHelper.ConvertToHtml(solution); File.WriteAllText("D:/temp/test.html", html); }
public override int Compare(DirectionWeight x, DirectionWeight y) { int val = 0; float d1 = (GraphSearch.fromPosition(x.x, x.y).euclidianDistanceFromTarget(x.goalX, x.goalY)); float d2 = (GraphSearch.fromPosition(y.x, y.y).euclidianDistanceFromTarget(y.goalX, y.goalY)); if (d1 < d2) { val = -1; } else if (d1 > d2) { val = 1; } else { val = 0; } return((x.weight - y.weight) * 10 + val); }
public void ResetMove(T id, GraphSearch search, Func <T, T, int> comparison = null) { Start = Vertexes[id]; Current = null; Search = search; Visited.Clear(); Comparison = comparison ?? new Func <T, T, int>((x, y) => x.CompareTo(y)); switch (search) { case GraphSearch.BFS: WaitingNodes = new WaitingQueue <Node>(); break; case GraphSearch.DFS: WaitingNodes = new WaitingStack <Node>(); break; default: break; } }
/* Maybe make the unit search for a valid target before shooting, as opposed to always shooting at the player */ public override void CastMainSpell() { base.CastMainSpell(); /* new animation */ if (GraphSearch .fromPosition(Map_position_x, Map_position_y) .manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y) <= MainSpell.CastRange) { MainSpell.loadInfo(new int[2] { Map_position_x, Map_position_y }, new int[2] { GameTools.Player.Map_position_x, GameTools.Player.Map_position_y }); ProjectileManager.getInstance().queueProjectile(MainSpell, game_object.transform.position, GameTools.Player.game_object.transform.position); } else if (GraphSearch .fromPosition(Map_position_x, Map_position_y) .manhattanDistanceFromTarget(GameTools.Base.Map_position_x, GameTools.Base.Map_position_y) <= MainSpell.CastRange) { MainSpell.loadInfo(new int[2] { Map_position_x, Map_position_y }, new int[2] { GameTools.Base.Map_position_x, GameTools.Base.Map_position_y }); ProjectileManager.getInstance().queueProjectile(MainSpell, game_object.transform.position, GameTools.Base.game_object.transform.position); } else { Debug.LogError("Not in either range"); } enemyAnimation.SetBool("Cast", true); }
public void InitSpawners(int playerlevel, int difficultyChange) { Debug.Log("Difficulty change " + difficultyChange); int SpawnerCount = 10 + difficultyChange; if (SpawnerCount < 5) { SpawnerCount = 5; } if (SpawnerCount > 20) { SpawnerCount = 20; } Debug.Log("SpawnerCount " + SpawnerCount); while (SpawnerCount > 0) { int randX = Random.Range(0, size_x); int randY = Random.Range(0, size_z); if (GraphSearch.fromPosition(randX, randY) .manhattanDistanceFromTarget(GameTools.Player.Map_position_x, GameTools.Player.Map_position_y) <= 25) { continue; } if (TileTools.IsLand(TileMapData[randX, randY])) { if (BonusTileData[randX, randY] == null && SpawnerMap[randX, randY] == null) { SpawnerCount--; EnemySpawner e = new EnemySpawner(randX, randY, playerlevel, difficultyChange); SpawnerMap[randX, randY] = e; Spawners.Add(e); } } } }
public void Execute_WhenTheSameStateOccursMultipleTimesAccordingToTheStateEqualityComparer_OnlyExpandsItOnce() { // Arrange var someState = fixture.Create<TestState>(); var someOtherState = fixture.Create<TestState>(); var equalToSomeState = fixture.Create<TestState>(); var equalityComparer = fixture.Create<Mock<IEqualityComparer<TestState>>>(); equalityComparer.Setup(comparer => comparer.Equals(It.IsAny<TestState>(), It.IsAny<TestState>())).Returns(false); equalityComparer.Setup(comparer => comparer.Equals(someState, equalToSomeState)).Returns(true); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(someState) .Returns(someOtherState) .Returns(equalToSomeState) .Returns(goalState); var subject = new GraphSearch<TestState>(strategy.Object, equalityComparer.Object); // Act subject.Execute(problem.Object); // Assert problem.Verify(prob => prob.IsGoalState(equalToSomeState), Times.Never); problem.Verify(prob => prob.GetSuccessors(equalToSomeState), Times.Never); }
public void Execute_AddsTheStartStateToTheFringe() { // Arrange problem.Setup(prob => prob.IsGoalState(It.IsAny<TestState>())).Returns(true); // avoid infinite loop var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert strategy.Verify(strat => strat.Add(startState), Times.Once()); }
private void ButtonSolveClick(object sender, RoutedEventArgs e) { if (_currentPolyLine.Points.Count >= 2) { _currentPolyLine.Points.Add(_currentPolyLine.Points[0]); } var initialState = new PathFindingState(new Search.Types.Point(100, 100)); var goalState = new PathFindingState(new Search.Types.Point(800, 600)); var environment = new PathFindingEnvironment(); foreach (var polyLine in _polyLines) { var points = polyLine.Points.Select(p => p).Distinct().ToList(); for (int i = 0; i < points.Count; i++) { for (int j = i + 1; j < points.Count; j++) { if (i == j) continue; var pointLine = new PointLine( new Point(points[i].X, points[i].Y), new Point(points[j].X, points[j].Y)); environment.PointLines.Add(pointLine); } } } var actionFunction = new PathFindingActionFunction(environment, goalState); var resultFunction = new PathFindingResultFunction(); var goalTest = new PathFindingGoalTest(goalState); var stepCost = new PathFindingStepCost(); var searchAlgorithm = new GraphSearch<PathFindingState, PathFindingAction>(); var problem = new Problem<PathFindingState, PathFindingAction>(initialState, actionFunction, resultFunction, goalTest, stepCost); var solution = searchAlgorithm.Search(problem); for (int i = 1; i < solution.Count; i++) { AddLine( solution[i - 1].State.Point.X, solution[i - 1].State.Point.Y, solution[i].State.Point.X, solution[i].State.Point.Y); } }
public void Execute_ExpandsStatesInOrderOfTheirAppearanceOffTheFringe() { // Arrange var stateBuilder = fixture.Build<TestState>(); var s1 = stateBuilder.Create(); var s2 = stateBuilder.Create(); var s3 = stateBuilder.Create(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(s1) .Returns(s2) .Returns(s3) .Returns(goalState); using (Sequence.Create()) { problem.Setup(prob => prob.GetSuccessors(startState)).InSequence().Returns(fixture.CreateMany<TestState>()); problem.Setup(prob => prob.GetSuccessors(s1)).InSequence().Returns(fixture.CreateMany<TestState>()); problem.Setup(prob => prob.GetSuccessors(s2)).InSequence().Returns(fixture.CreateMany<TestState>()); problem.Setup(prob => prob.GetSuccessors(s3)).InSequence().Returns(fixture.CreateMany<TestState>()); var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert problem.Verify(); } }
public void Execute_WhenTheStartStateIsNotAGoalState_ExpandsTheStartState() { // Arrange var subject = new GraphSearch<TestState>(strategy.Object); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(goalState); // Act subject.Execute(problem.Object); // Assert problem.Verify(prob => prob.GetSuccessors(startState), Times.Once()); }
public void Execute_AddsExpandedStatesToTheFringe() { // Arrange var stateBuilder = fixture.Build<TestState>(); var s1 = stateBuilder.Create(); var s2 = stateBuilder.Create(); var s3 = stateBuilder.Create(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(s1) .Returns(s2) .Returns(s3) .Returns(goalState); problem.Setup(prob => prob.GetSuccessors(startState)).Returns(new[] { s1 }); problem.Setup(prob => prob.GetSuccessors(s1)).Returns(new[] { s2, s3 }); problem.Setup(prob => prob.GetSuccessors(s2)).Returns(fixture.CreateMany<TestState>()); problem.Setup(prob => prob.GetSuccessors(s3)).Returns(new[] { goalState }); using (Sequence.Create()) { strategy.Setup(strat => strat.Add(s1)).InSequence(); strategy.Setup(strat => strat.Add(s2)).InSequence(); strategy.Setup(strat => strat.Add(s3)).InSequence(); strategy.Setup(strat => strat.Add(goalState)).InSequence(); var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert strategy.VerifyAll(); } }
public void Execute_WhenTheStartStateIsNotAGoalState_AddsItsSucessorsToTheFringe() { // Arrange var succesors = fixture.CreateMany<TestState>(3).ToArray(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(succesors[0]) .Returns(succesors[1]) .Returns(succesors[2]) .Returns(goalState); problem.Setup(prob => prob.GetSuccessors(startState)).Returns(succesors); var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert strategy.Verify(strat => strat.Add(succesors[0]), Times.Once()); strategy.Verify(strat => strat.Add(succesors[1]), Times.Once()); strategy.Verify(strat => strat.Add(succesors[2]), Times.Once()); }
public void Execute_WhenTheStartStateIsAGoalState_DoesNotExpandAnyStates() { // Arrange var subject = new GraphSearch<TestState>(strategy.Object); strategy.Setup(strat => strat.GetNext()).Returns(startState); problem.Setup(prob => prob.IsGoalState(startState)).Returns(true); // Act subject.Execute(problem.Object); // Assert problem.Verify(prob => prob.GetSuccessors(It.IsAny<TestState>()), Times.Never()); }
public void Execute_ReturnsTheFirstGoalStateOffTheFringe() { // Arrange var stateBuilder = fixture.Build<TestState>(); var secondGoal = stateBuilder.Create(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(stateBuilder.Create()) .Returns(stateBuilder.Create()) .Returns(goalState) .Returns(stateBuilder.Create()) .Returns(secondGoal); problem.Setup(prob => prob.IsGoalState(secondGoal)).Returns(true); var subject = new GraphSearch<TestState>(strategy.Object); // Act var result = subject.Execute(problem.Object); // Assert Assert.Equal(goalState, result); }
public void Execute_WhenProblemIsNull_ThrowsAnArgumentNullException() { // Arrange var subject = new GraphSearch<TestState>(strategy.Object); // Act Action act = () => subject.Execute(null); // Assert var ex = Assert.Throws<ArgumentNullException>(act); Assert.Equal(nameof(problem), ex.ParamName); }
public void Execute_WhenTheFringeBecomesEmptyWithNoGoalStateFound_ThrowsANoSolutionPossibleException() { // Arrange strategy.SetupSequence(strat => strat.IsEmpty()) .Returns(false) .Returns(false) .Returns(true); var subject = new GraphSearch<TestState>(strategy.Object); // Act Action act = () => subject.Execute(problem.Object); // Assert var ex = Assert.Throws<NoSolutionPossibleException>(act); Assert.NotNull(ex.Message); }
public void Execute_DoesNotExpandStatesAfterTheGoalStateIsFound() { // Arrange var afterGoal = fixture.Create<TestState>(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(goalState) .Returns(afterGoal); var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert problem.Verify(prob => prob.IsGoalState(afterGoal), Times.Never); problem.Verify(prob => prob.GetSuccessors(afterGoal), Times.Never); }
public void Execute_WhenTheSameStateOccursMultipleTimes_OnlyExpandsItOnce() { // Arrange var someState = fixture.Create<TestState>(); strategy.SetupSequence(strat => strat.GetNext()) .Returns(startState) .Returns(someState) .Returns(someState) .Returns(goalState); var subject = new GraphSearch<TestState>(strategy.Object); // Act subject.Execute(problem.Object); // Assert problem.Verify(prob => prob.IsGoalState(someState), Times.Once); problem.Verify(prob => prob.GetSuccessors(someState), Times.Once); }