public void LastAndReverseTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable where boundary.Contains(step) orderby step.GetManhattanDistance(goal), step.GetEuclideanDistance(goal) select step; Assert.Equal(solution.Reverse().Last(), queryable.From); }
public void AnyTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable where boundary.Contains(step) orderby step.GetManhattanDistance(goal), step.GetEuclideanDistance(goal) select step; Assert.True(solution.Any()); }
public void CountTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable where boundary.Contains(step) orderby step.GetManhattanDistance(goal), step.GetEuclideanDistance(goal) select step; // Since there are no obstacles between start and goal, // the total number of solution steps should be equal to their Manhattan distance + 1. Assert.Equal(start.GetManhattanDistance(goal) + 1, solution.Count()); }
public void IDAStarWithoutOrderByTest() { var queryable = HeuristicSearch.IterativeDeepeningAStar(start, goal, (step, lv) => step.GetFourDirections(unit)); var obstacles = new[] { new Point(5, 5), new Point(6, 6), new Point(7, 7), new Point(8, 8), new Point(9, 9) }; var solution = from step in queryable from obstacle in obstacles where step != obstacle select step; var exception = Assert.Throws <InvalidOperationException>(() => solution.ToList()); Assert.StartsWith("Unable to evaluate steps.", exception.Message); }
public void ContainsTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable.Contains(boundary.GetAvailablePoints(unit)) orderby step.GetManhattanDistance(goal) select step; var actual = solution.ToArray(); Assert.Equal(actual.First(), queryable.From); Assert.Equal(actual.Last(), queryable.To); }
public void AStarWithoutOrderByTest() { var queryable = HeuristicSearch.AStar(start, goal, (step, lv) => step.GetFourDirections(unit)); var obstacles = new[] { new Point(5, 5), new Point(6, 6), new Point(7, 7), new Point(8, 8), new Point(9, 9) }; var solution = from step in queryable from obstacle in obstacles where step != obstacle select step; var actual = solution.ToList(); Assert.Equal(actual.First(), queryable.From); Assert.Equal(actual.Last(), queryable.To); }
public void OrderByThenByComparerTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable where boundary.Contains(step) orderby step.GetManhattanDistance(goal), step.GetEuclideanDistance(goal) select step; var actual = solution.ToArray(); Assert.IsType <CombinedComparer <Point, Point> >(solution.NodeComparer); Assert.Equal(actual.First(), queryable.From); Assert.Equal(actual.Last(), queryable.To); }
public RandomWalksFromGoalPathStateSpaceEnumerator(Problem problem, DomainDependentSolver domainDependentSolver) : base(problem) { domainDependentSolver.SetProblem(problem); this.goalPathFinder = new HillClimbingSearch(problem, new HeuristicWrapper(domainDependentSolver)); domainSolver = domainDependentSolver; goalPath = findGoalPath(); StateSpaceEnumeratos = goalPath.Select(s => { var enume = new RandomWalkStateSpaceEnumerator(problem); enume.initialState = s; return(enume); }).ToList(); }
public IEnumerator <object[]> GetEnumerator() { foreach (var setting in MapData.GetStartGoalCombinations()) { var start = setting.Start; var goal = setting.Goal; var queryable = HeuristicSearch.RecursiveBestFirstSearch(start, goal, (step, lv) => step.GetFourDirections(MapData.Unit)); var solution = from step in queryable.Except(MapData.Obstacles) where step.X >= 0 && step.Y >= 0 && step.X <= 40 && step.Y <= 40 orderby step.GetManhattanDistance(goal) select step; yield return(new object[] { start, goal, solution.ToArray() }); } }
static void Main(string[] args) { var start = new Vector2(5, 5); var goal = new Vector2(35, 35); var unit = 1; var queryable = HeuristicSearch.AStar(start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable.Except(GetObstacles()) where step.X >= 0 && step.Y >= 0 && step.X <= 40 && step.Y <= 40 orderby step.GetManhattanDistance(goal) select step; foreach (var step in solution) { Console.WriteLine(step); } }
public void SelectManyTest(string algorithmName) { var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit)); var obstacles = new[] { new Point(5, 5), new Point(6, 6), new Point(7, 7), new Point(8, 8), new Point(9, 9) }; var solution = from step in queryable from obstacle in obstacles where step != obstacle orderby step.GetManhattanDistance(goal) select step; var actual = solution.ToArray(); Assert.Empty(actual.Intersect(obstacles)); Assert.Equal(actual.First(), queryable.From); Assert.Equal(actual.Last(), queryable.To); }
public static AlgorithmSolution Find(PathfindingSettings settings, int mapWidth, int mapHeight, IEnumerable <Point> obstacles) { var observer = new AlgorithmObserverFactory(); var start = new Point(settings.FromX, settings.FromY); var goal = new Point(settings.GoalX, settings.GoalY); var boundary = new Rectangle(0, 0, mapWidth, mapHeight); var unit = 1; var queryable = HeuristicSearch.Use(settings.Algorithm, start, goal, (step, i) => step.GetFourDirections(unit), null, observer); var solution = ApplyHeuristicFunction(queryable.Except(obstacles).Where(boundary.Contains), settings.Heuristics); return(new AlgorithmSolution() { Details = observer.Details, Solution = solution.ToArray(), NumberOfEstimatedNodes = observer.Estimated.Count, }); }
static void Main(string[] args) { var start = new Point(5, 5); var goal = new Point(35, 35); var boundary = new Rectangle(0, 0, 40, 40); var unit = 1; var queryable = HeuristicSearch.AStar(start, goal, (step, lv) => step.GetFourDirections(unit)); var solution = from step in queryable.Except(GetMapObstacles()) where boundary.Contains(step) orderby step.GetManhattanDistance(goal) select step; foreach (var step in solution) { Console.WriteLine(step); } }
public AStarValidityTest() { var mapData = TestHelper.LoadMapData(); _start = mapData.Start; _goal = mapData.Goal; _obstacles = mapData.Obstacles; _unit = 1f; var queryable = HeuristicSearch.AStar(_start, _goal, (step, lv) => step.GetFourDirections(_unit)); var solution = from step in queryable.Except(mapData.Obstacles) where step.X >= 0 && step.Y >= 0 && step.X <= 40 && step.Y <= 40 orderby step.GetManhattanDistance(_goal) select step; _path = solution.ToList(); }
public void TestFirstStateEqualToStart(string algorithmName) { var factory = new Mock <IAlgorithmObserverFactory <Point> >(); var progress = new Mock <IProgress <AlgorithmState <Point, Point> > >(); factory.Setup(f => f.Create(It.IsAny <HeuristicSearchBase <Point, Point> >())).Returns(() => progress.Object); progress.Setup(p => p.Report(It.IsAny <AlgorithmState <Point, Point> >())); var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit), null, factory.Object); var obstacles = new[] { new Point(5, 5), new Point(6, 6), new Point(7, 7), new Point(8, 8), new Point(9, 9) }; var solution = from step in queryable.Except(obstacles) where boundary.Contains(step) orderby step.GetManhattanDistance(goal) select step; Assert.NotEmpty(solution); progress.Verify(p => p.Report(It.Is <AlgorithmState <Point, Point> >(s => s.Node.Step == start && s.Node.Level == 0 && s.Flag == AlgorithmFlag.InProgress)), Times.Once); }
public void TestIProgressOnlyCreatedOnce(string algorithmName) { var factory = new Mock <IAlgorithmObserverFactory <Point> >(); var progress = new Progress <AlgorithmState <Point, Point> >(); progress.ProgressChanged += (o, e) => Debug.WriteLine("{0}\t{1} ({2})", e.Node.Step, e.Node.Level, nameof(progress.ProgressChanged)); factory.Setup(f => f.Create(It.IsAny <HeuristicSearchBase <Point, Point> >())).Returns(() => progress); var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit), null, factory.Object); var obstacles = new[] { new Point(5, 5), new Point(6, 6), new Point(7, 7), new Point(8, 8), new Point(9, 9) }; var solution = from step in queryable where !obstacles.Contains(step) orderby step.GetManhattanDistance(goal) select step; Assert.NotEmpty(solution); factory.Verify(f => f.Create(It.IsAny <HeuristicSearchBase <Point, Point> >()), Times.Once); }
public void TestLastFlagNotFound(string algorithmName) { var factory = new Mock <IAlgorithmObserverFactory <Point> >(); var progress = new Mock <IProgress <AlgorithmState <Point, Point> > >(); var actual = default(AlgorithmFlag?); var expected = (AlgorithmFlag?)AlgorithmFlag.NotFound; factory.Setup(f => f.Create(It.IsAny <HeuristicSearchBase <Point, Point> >())).Returns(() => progress.Object); progress.Setup(p => p.Report(It.IsAny <AlgorithmState <Point, Point> >())).Callback <AlgorithmState <Point, Point> >(s => actual = s.Flag); var queryable = HeuristicSearch.Use(algorithmName, start, goal, (step, lv) => step.GetFourDirections(unit), null, factory.Object); var obstacleX = start.X + (start.X + goal.X) / 2; var obstacles = from y in Enumerable.Range(0, boundary.Height + 1) select new Point(obstacleX, y); // Build a wall that cannot be bypassed in the middle of start and goal. var solution = from step in queryable.Except(obstacles) where boundary.Contains(step) orderby step.GetManhattanDistance(goal) select step; Assert.Empty(solution); Assert.Equal(expected, actual); progress.Verify(p => p.Report(It.Is <AlgorithmState <Point, Point> >(s => s.Flag == expected && s.Node == null)), Times.Once); }
static void Main(string[] args) { // StringProblems //Test calls for Reverse string string input = "jacob"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jake"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = ""; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jdshjdh@#$%^&)"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); ReplaceSpaces.TestReplaceSpacesInplace(); Anagrams.TestIsAnagramAlgo(); StringRotation.TestIsThisRotatedString(); RemoveDuplicates.TestRemoveDuplicatesFromString(); StringToLongConverter.TestStringToLong(); RegexMatching.TestMatch(); SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray(); SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray(); PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue(); PalindromeInStringPermutation.TestPalindromeInStringPermutation(); EditDistanceBetweenStrings.TestEditDistanceBetweenStrings(); AnagramIsPalindrome.TestAnagramIsPalindrome(); GreatestPalindrome.TestGreatestPalindrome(); ReverseStringWithoutVowels.TestReverseStringWithoutVowels(); LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars(); // Pattern Matching NativePatternMatching.TestNativePatternMatching(); KMPPatternMatching.TestKMPPatternMatching(); BoyerMoorePatternMatching.TestPatternMatching(); RabinKarp.TestRabinKarp(); //Console.ReadLine(); //Array Problems ArrayOfNumsIncrement.TestIncrementArrayOfNumbers(); MajorityElement.TestFindMajorityElement(); Merge2SortedArrays.TestMergeSortedArrays(); MaxDistanceInArray.TestMaxDistanceInArray(); MovingAverage.TestMovingAverage(); TotalAverage.TestTotalAverage(); ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight(); WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram(); CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum(); //Median.TestGetMedianOf2SortedArray(); // Sorting Problems SelectionSort.TestSorting(); BubbleSort.TestSorting(); InsertionSort.TestSorting(); ShellSort.TestSorting(); MergeSort.TestMergeSort(); QuickSort.TestQuickSort(); HeapSortTester.TestHeapSort(); CountingSort.TestSorting(); RadixSort.TestRadixSort(); DutchNationalFlag.TestDutchNationalFlag(); SortedSquares.TestSortedSquares(); // Matrix Problem Rotate_Matrix_90_degree.TestRotateMatrix(); Matrix_Column_Rows_0.TestMakeRowColZero1(); Matrix_Column_Rows_0.TestMakeRowColZero2(); RotateMatrix180.TestRotateMatrix180(); SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements(); SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix(); SearchWordInMatrix.TestSearchWordInMatrix(); MaxOnesInRow.TestMaxOnesInRow(); MatrixAsTriangle.TestMatrixAsTriangle(); MinRangeInMatrix.TestMinRangeInMatrix(); PrintMatrixAsSnake.TestPrintMatrixAsSnake(); PrintMatrixInSpiral.TestPrintMatrixInSpiral(); MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix(); TicTacToeWinner.TestTicTacToeWinner(); WaterfallCreation.TestWaterfallCreation(); // Linked list Problems DeleteLinkedListNode.TestDeleteFirstNode(); DeleteDuplicatesFromLinkedList.TestDeleteDuplicates(); NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList(); DeleteNodeWithDirectReference.TestDeleteNode(); AddNumbers.TestAddNumbersRepresentedByLinkedList(); CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode(); CommonElementInTwoLinkedList.TestCommonElement(); ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes(); MergeSortedLinkedList.TestMerge(); CycleInLinkedList.TestStartOfCycleInLinkedList(); MedianForCircularLinkedList.TestGetMedian(); ReverseLinkedList.TestReverseLinkedList(); SortedCircularLinkedList.TestCircularLinkedList(); // stack and queue problem ThreeStackWithOneArray.TestThreeStackWithOneArray(); StackWithMinElement.TestStackWithMinElement(); StackOfPlates.TestStackOfPlates(); SortAStack.TestSortAStackAscending(); WellFormedExpression.TestWellFormedExpression(); QueueVia2Stack.TestQueueVia2Stack(); LRUCache.TestLRUCache(); EvaluatePrefixNotation.TestGetPrefixNotationResult(); EvaluateInflixNotation.TestGetInflixNotationResults(); EvaluatePostfixNotation.TestGetPostfixNotationResult(); TestCircularQueue.TestCircularQueueWithDifferentCases(); LargestAreaInHistogram.TestLargestAreaInHistogram(); TextEditerWithUndo.TestTextEditerWithUndo(); //Recursion Problem TowerOfHanoi.TestTowerOfHanoi(); MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums(); // Back tracking problems Sudoku.TestSudokuSolver(); HamiltonianCycle.TestHamiltonianCycle(); GraphColoringWithMColors.TestGraphColoringWithMColors(); MakeLargestIsland.TestMakeLargestIsland(); //Misc Problem MinNumOfCoins.TestMinNumOfCoins(); IsPrime.TestCheckPrime(); SquareRoot.TestCalculateSquareRoot(); CreditCardCheck.TestLuhnAlgo(); ExcelFirstRowConversion.TestCovertExcelColumnToLong(); Skyline.TestSkyline(); SumOfSquaresWithoutMultiplication.TestSumOfSquares(); MergeIntervals.TestMergeIntervals(); WidthOfCalendar.TestWidthOfCalendar(); JosephusProblem.TestJosephusProblem(); // Permutation and Combination problem ShuffleAList.TestFisherYatesAlgo(); CombinationsOfBinaryString.TestCombinationsOfBinaryString(); AllCombinationsOfString.TestAllCombinationsOfString(); AllPermutationsOfString.TestAllPermutationsOfString(); PhoneNumberToWords.TestPhoneNumberToWords(); AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits(); DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff(); PowerSet.TestPowerSet(); AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis(); GoodDiceRoll.TestGoodDiceRoll(); PermutationsOfValidTime.TestPermutationsOfValidTime(); // Tree Problems TreeFromExpression.TestCreateTreeFromExpression(); TestBinarySearchTree.TestDifferentOperationsOnBST(); AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST(); CheckBTisBST.TestCheckBTisBST(); MaxSumOnTreeBranch.TestMaxSum(); WalkTheTree.TestWalkTheTree(); SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST(); CheckIfTheTreeIsBalanced.TestIsTreeBalanced(); LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth(); PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel(); PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally(); TreeSubtreeOfAnother.TestMatchTree(); AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT(); AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT(); LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT(); ExteriorOfBT.TestPrintExteriorOfBT(); DepthOfTree.TestGetDepthOfTree(); TreeToColumns.TestTreeToColumns(); KthSmallestElementFromBST.TestKthSmallestElementFromBST(); MakeBSTFromPreOrder.TestMakeBSTFromPreOrder(); MirrorATree.TestMirrorATree(); CloneABTWithRandPointer.TestCloneABTWithRandPointer(); TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder(); TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder(); TreePathSumsToValue.TestTreePathSumsToValue(); AllPathInNArayTree.TestAllPathInNArayTree(); SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree(); SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree(); AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree(); AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT(); // Trie problems CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie(); // ToDo: have a problem of suffix trees ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet(); // Dynamic Programming problems LongestCommonSubsequence.TestGetLongestCommonSubsequence(); LongestPalindromeSubString.TestGetLongestPalindromeSubString(); LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence(); MaximumAs.TestGetMaximumAs(); MinNumberOfJumps.TestGetMinimumNumberOfJumps(); LongestCommonSubString.TestGetLongestCommonSubString(); KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight(); TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits(); WordBreaking.TestBreakTheWords(); DistanceOfWords.TestDistanceOfWords(); LongestIncreasingSubSequence.TestLongestIncreasingSubSequence(); MinCostPath.TestMinCostPath(); DifferentWaysForCoinChange.TestDifferentWaysForCoinChange(); MatrixMultiplication.TestMatrixMultiplication(); BinomialCoefficient.TestBinomialCoefficient(); BoxStacking.TestBoxStacking(); WordWrapping.TestWordWrapping(); MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes(); LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum(); PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets(); MaxSumRectangle.TestMaxSumRectangle(); RegularExpressionMatch.TestRegularExpressionMatch(); NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares(); LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString(); StringDecodeAsAlphabets.TestStringDecodeAsAlphabets(); BalloonBursting.TestBalloonBursting(); TravellingSalesmanProblem.TestTravellingSalesmanProblem(); MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements(); MaxPathThroughMatrix.TestMaxPathThroughMatrix(); BrickLaying.TestBrickLaying(); JobSchedullingWithConstraints.TestJobSchedullingWithConstraints(); EggDropMinTrials.TestEggDropMinTrials(); // Graph Problems ShortestPath.TestGetShortestPathBetween2Vertex(); CycleInDirectedGraph.TestIsCycleInDirectedGraph(); CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph(); SolveAMaze.TestSolveAMaze(); AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex(); AllPaths.TestGetAllPathsInGraphFromStartVertex(); ColorVertices.TestColorVerticesWithDifferentColor(); CheckBipartiteGraph.TestCheckBipartiteGraph(); TransformOneWordToAnother.TestGetTransformation(); ConstraintsVerification.TestConstraintsVerification(); ExtendedContactsInSocialNetwork.TestComputeExtendedContacts(); CourseScheduling.TestCourseScheduling(); SnakeAndLadder.TestSnakeAndLadder(); IsGraphATree.TestIsGraphATree(); ReverseGraph.TestReverseGraph(); StronglyConnectedGraph.TestStronglyConnectedGraph(); ConnectedComponents.TestConnectedComponents(); ContinentalDivide.TestContinentalDivide(); CloneGraph.TestCloneGraph(); Wordament.TestWordament(); // ShortestPathAlgo FloydWarshall.TestFloydWarshall(); DijkstraAlgorithm.TestDijkstraAlgorithm(); BellmanFord.TestBellmanFord(); TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix(); HeuristicSearch.TestHeuristicSearch(); AStar.TestAStar(); ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved(); ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates(); //MaxFlow FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp(); MinCut.TestMinCut(); MaximumBipartiteMatching.TestMaximumBipartiteMatching(); //Minimum Spanning Tree KruskalAlgorithm.TestKruskalAlgorithm(); PrimsAlgorithm.TestPrimsAlgorithm(); //Heap problems BasicMaxHeap.TestMaxHeap(); BasicMinHeap.TestMinHeap(); TestMinHeapMap.DoTest(); TestPriorityQueue.Run(); MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers(); //DisjointSets TestingDisjointSet.Run(); //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it //Geometry ClosestPairOfPoints.TestClosestPairOfPoints(); RectangleIntersection.TestRectangleIntersection(); LineSegmentIntersection.TestLineSegmentIntersection(); ConvexHull.TestConvexHull(); KClosestPointToOrigin.TestKClosestPointToOrigin(); //Greedy Algorithm HuffmanCoding.TestHuffmanCoding(); //Randomized Algorithm RandomGeneration.TestRandomGeneration(); // Bit Algorithms IntHaveOppositeSigns.TestIntHaveOppositeSigns(); Parity.TestParity(); //Math Problem ZerosInFactorial.TestZerosInFactorial(); GetAllPrimeFactors.TestGetAllPrimeFactors(); NumberOfFactors.TestNumberOfFactors(); AllFactors.TestAllFactors(); MultiplyLongNumbers.TestMultiplyLongNumbers(); NextLargestPermutation.TestNextLargestPermutation(); AllPrimesTillN.TestAllPrimesTillN(); PascalsTriangle.TestPascalsTriangle(); SubtractLongNumbers.TestSubtractLongNumbers(); //Search problems SearchInSortedRotatedArray.TestSearchInSortedRotatedArray(); KClosestElementInArray.TestKClosestElementInArray(); SearchInSortedMatrix.TestSearchInSortedMatrix(); BinarySearchUnbounded.TestBinarySearchUnbounded(); LinkedListSublistSearch.TestLinkedListSublistSearch(); NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray(); GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray(); //Distributed algorithms KWayMerge.TestKWayMerge(); Console.ReadLine(); }
static void Main(string[] args) { var boundary = new Rectangle(0, 0, MapWidth, MapWidth); var presentation = new char[MapHeight][]; while (true) { var queryable = default(HeuristicSearchBase <Point, Point>); var solution = default(HeuristicSearchBase <Point, Point>); var counter = 0; var mapData = LoadMapData(); for (var y = 0; y < MapHeight; y++) { if (presentation[y] == null) { presentation[y] = new char[MapWidth]; } for (var x = 0; x < MapWidth; x++) { var point = new Point(x, y); if (mapData.Obstacles.Contains(point)) { presentation[y][x] = ObstacleSymbol; } else if (point == mapData.Start) { presentation[y][x] = StartSymbol; } else if (point.Equals(mapData.Goal)) { presentation[y][x] = GoalSymbol; } else { presentation[y][x] = SpaceSymbol; } } } Console.WriteLine("A)* Search"); Console.WriteLine("B)est-first Search"); Console.WriteLine("R)ecursive Best-first Search"); Console.WriteLine("I)terative Deepening AStar Search"); Console.Write("Select an algorithm: "); // Initial the algorithm. switch (Console.ReadKey().Key) { case ConsoleKey.A: queryable = HeuristicSearch.AStar(mapData.Start, mapData.Goal, GetNextSteps); break; case ConsoleKey.B: queryable = HeuristicSearch.BestFirstSearch(mapData.Start, mapData.Goal, GetNextSteps); break; case ConsoleKey.I: queryable = HeuristicSearch.IterativeDeepeningAStar(mapData.Start, mapData.Goal, GetNextSteps); break; case ConsoleKey.R: queryable = HeuristicSearch.RecursiveBestFirstSearch(mapData.Start, mapData.Goal, GetNextSteps); break; default: continue; } Console.WriteLine(); Console.WriteLine("C)hebyshev Distance Comparer"); Console.WriteLine("E)uclidean Distance Comparer"); Console.WriteLine("M)anhattan Distance Comparer"); Console.Write("Select comparer: "); // Compare two positions and the goal position with selected distance. switch (Console.ReadKey().Key) { case ConsoleKey.C: solution = from step in queryable.Except(mapData.Obstacles) where boundary.Contains(step) orderby step.GetChebyshevDistance(mapData.Goal) select step; break; case ConsoleKey.E: solution = from step in queryable.Except(mapData.Obstacles) where boundary.Contains(step) orderby step.GetEuclideanDistance(mapData.Goal) select step; break; case ConsoleKey.M: solution = from step in queryable.Except(mapData.Obstacles) where boundary.Contains(step) orderby step.GetManhattanDistance(mapData.Goal) select step; break; default: continue; } Console.WriteLine(); foreach (var step in solution) { if (step != mapData.Start && step != mapData.Goal) { presentation[(int)step.Y][(int)step.X] = PathSymbol; } counter++; } Array.ForEach(presentation, row => Console.WriteLine(string.Join(" ", row))); Console.WriteLine("Total steps: {0}", counter); } }
static void Main(string[] args) { while (true) { // http://www.8puzzle.com/images/8_puzzle_start_state_a.png var initial = new BoardState(new[] { new Point(1, 2), // empty square new Point(0, 1), // square 1 new Point(0, 0), // square 2 new Point(2, 0), // square 3 new Point(2, 1), // square 4 new Point(2, 2), // square 5 new Point(1, 1), // square 6 new Point(0, 2), // square 7 new Point(1, 0), // square 8 }); // http://www.8puzzle.com/images/8_puzzle_goal_state_a.png var goal = new BoardState(new[] { new Point(1, 1), // empty square new Point(0, 0), // square 1 new Point(1, 0), // square 2 new Point(2, 0), // square 3 new Point(2, 1), // square 4 new Point(2, 2), // square 5 new Point(1, 2), // square 6 new Point(0, 2), // square 7 new Point(0, 1), // square 8 }); Console.WriteLine("A)* Search"); Console.WriteLine("B)est-first Search"); Console.WriteLine("I)terative Deepening AStar Search"); Console.WriteLine("R)ecursive Best-first Search"); Console.Write("Select an algorithm: "); var queryable = default(HeuristicSearchBase <BoardState, BoardState>); // Initialize the algorithm with the callback that gets all valid moves. switch (Console.ReadKey().Key) { case ConsoleKey.A: queryable = HeuristicSearch.AStar(initial, goal, (board, lv) => board.GetNextSteps()); break; case ConsoleKey.B: queryable = HeuristicSearch.BestFirstSearch(initial, goal, (board, lv) => board.GetNextSteps()); break; case ConsoleKey.I: queryable = HeuristicSearch.IterativeDeepeningAStar(initial, goal, (board, lv) => board.GetNextSteps()); break; case ConsoleKey.R: queryable = HeuristicSearch.RecursiveBestFirstSearch(initial, goal, (board, lv) => board.GetNextSteps()); break; default: continue; } Console.WriteLine(); // GetSumOfDistances() calculates the sum of Manhattan distance // between each of square and its goal. // ------------------------------------------------- var solution = from board in queryable orderby board.GetSumOfDistances(goal) select board; // ------------------------------------------------- // Print out the solution. foreach (var board in solution) { Console.WriteLine(board); } } }