Ejemplo n.º 1
0
        public static PsmDataCollection ExtractPsmData(XElement results, SearchAlgorithm searchAlgorithm)
        {
            PsmDataCollection psms = new PsmDataCollection();
            PsmData           psm;

            if (searchAlgorithm == SearchAlgorithm.XTandem)
            {
                foreach (var x in results.Descendants("group").Where(x => x?.Element("protein") != null))
                {
                    psm = new PsmData();

                    psm.Id = Convert.ToInt32(x.Attribute("id").Value);

                    psm.Decoy = x.Attribute("label").Value.StartsWith("DECOY_");

                    // it is possible for each "group" in the pepXML file to have more than one protein. This just means the peptide isn't
                    // unique to a single protein. However, the scoring and modifications are identical (since it is the same PSM), so we
                    // can just use the first protein. That is what we do below.
                    XElement domain = x.Element("protein").Element("peptide").Element("domain");

                    psm.Seq = domain.Attribute("seq").Value;

                    psm.Start = Convert.ToInt32(domain.Attribute("start").Value);

                    psm.End = Convert.ToInt32(domain.Attribute("end").Value);

                    psm.Hyperscore = Convert.ToDouble(domain.Attribute("hyperscore").Value);

                    psm.ExpectationValue = Convert.ToDouble(domain.Attribute("expect").Value);

                    psm.MassDrift = (Convert.ToDouble(x.Attribute("mh")?.Value) - Convert.ToDouble(domain?.Attribute("mh").Value)) /
                                    Convert.ToDouble(domain?.Attribute("mh").Value) * 1e6;

                    psm.Charge = Convert.ToInt32(x.Attribute("z").Value);

                    psm.MissedCleavages = GetMissedCleavages(psm.Seq);

                    // add the modifications, if there are any
                    if (domain?.Elements("aa") != null)
                    {
                        foreach (XElement aa in domain.Elements("aa"))
                        {
                            Modification mod = new Modification();
                            // we convert the location to a zero-based index of the peptide
                            mod.Loc = Convert.ToInt32(aa.Attribute("at").Value) - psm.Start;

                            mod.AA = aa.Attribute("type").Value;

                            mod.Mass = Convert.ToDouble(aa.Attribute("modified").Value);

                            psm.Mods.Add(mod);
                        }
                    }

                    psms.Add(psm.Id, psm);
                }
            }

            return(psms);
        }
Ejemplo n.º 2
0
    public void OnSearchSelect(int index)
    {
        switch (index)
        {
        case 0:
            Search = SearchDFS.Search;

            break;

        case 1:
            Search = SearchBFS.Search;

            break;

        case 2:
            Search = SearchDijiksta.Search;

            break;

        case 3:
            Search = SearchAStar.Search;

            break;
        }
    }
Ejemplo n.º 3
0
    // Use this for initialization
    void Start()
    {
        search            = GetSearchAlgorithm(); //
        TargetOptmisation = GetOptimisationAlgorithm();
        targets           = null;



        //Node start_pos = GridMap.instance.NodeFromWorldPoint (transform.position);
        //transform.position = start_pos.worldPosition + new Vector3(0f,0.5f,0f);

        currentCost      = 0;
        moveToNext       = false;
        isMoving         = false;
        costsNotComputed = true;
        isAtTarget       = false;

        gameObject.GetComponent <Renderer> ().material.color = agentColor;

        getCostTable();

        Debug.Log("Done");

        TargetOptmisation.setDistanceMatrix(dMatrix);
    }
Ejemplo n.º 4
0
    /*
     * this method will be called from a UI.Button, so it accessibility modifier must be public.
     * but it's cool if it called in another way, because it doesn't depends on ui actions.
     */
    public void StartSearching()
    {
        SetUIActivity(false);
        Log("Searching...", Color.white);

        // destroying previous children of root node
        DestroyChilrenNodes();

        Init();

        SearchAlgorithm algorithm = (SearchAlgorithm)m_AlgorithmOptions.value;

        switch (algorithm)
        {
        case SearchAlgorithm.BreadthFirstSearch:
            StartCoroutine(BreadthFirstSearch(m_RootNode));
            break;

        case SearchAlgorithm.DepthFirstSearch:
            StartCoroutine(DepthFirstSearch(m_RootNode));
            break;

        default:
            SetUIActivity(true);
            Log($"[{Regex.Replace(algorithm.ToString(), "(\\B[A-Z])", " $1")}] is not implemented yet!", Color.red);
            break;
        }
    }
Ejemplo n.º 5
0
        public Element?[] Spell(string word, SearchAlgorithm algorithm)
        {
            Dictionary <int, Element> indexed = new Dictionary <int, Element>();

            word = Regex.Replace(word.ToLower(), "[^a-z\\s]", "");
            switch (algorithm)
            {
            case SearchAlgorithm.ElementBased:
                foreach (Element element in elements)
                {
                    string symbol = element.Symbol.ToLower();
                    if (word.Contains(symbol))
                    {
                        foreach (int i in word.IndexOfAll(symbol))
                        {
                            indexed.Add(i, element);
                        }
                        word = word.Replace(symbol, new string ('_', symbol.Length));
                    }
                }
                break;

            case SearchAlgorithm.ChunkSearch:
                int maxElementLength = elements.Max(e => e.Symbol.Length);
                for (int searchLength = maxElementLength; searchLength > 0; searchLength--)
                {
                    Element[] currentElements = elements.Where(e => e.Symbol.Length == searchLength).ToArray();
                    for (int x = 0; x < word.Length - searchLength + 1; x++)
                    {
                        foreach (Element currentElement in currentElements)
                        {
                            if (word.Substring(x, searchLength) == currentElement.Symbol.ToLower())
                            {
                                indexed.Add(x, currentElement);
                                ArrayList tmpList = new ArrayList(((ICollection)(Array)word.ToCharArray()));
                                tmpList.SetRange(x, (ICollection)(Array) new string('_', searchLength).ToCharArray());
                                word = new string(Array.ConvertAll(tmpList.ToArray(), item => (char)item));
                            }
                        }
                    }
                }
                break;
            }
            List <Element?> spelled = new List <Element?>();
            int             max     = indexed.Max(item => item.Key);
            Element         value;

            for (int i = 0; i <= max; i++)
            {
                if (indexed.TryGetValue(i, out value))
                {
                    spelled.Add(value);
                }
                else if (word[i] == ' ')
                {
                    spelled.Add(null);
                }
            }
            return(spelled.ToArray());
        }
Ejemplo n.º 6
0
    // Use this for initialization
    void Start()
    {
        search = GetSearchAlgorithm();
        TestWriter.Start(SceneManager.GetActiveScene().name + "_" + search.getName() + ".csv");
        targets = GetAllTargets();
        targets.Sort(GridMap.SortByName);
        UpdateStartTargetPositions();


        Node start_pos = GridMap.instance.NodeFromWorldPoint(transform.position);

        transform.position = start_pos.worldPosition + new Vector3(0f, 1f, 0f);

        currentCost                  = 0;
        moveToNext                   = false;
        isMoving                     = false;
        isDead                       = false;
        isAtTarget                   = false;
        currentForce                 = totalEnergy;
        currentEnergyExpanded        = totalEnergy;
        updateEnergyExpandedInterval = Mathf.Max(Mathf.RoundToInt(search.GetMaxNumberOfExpandedNodes() / totalEnergy), 1);
        updateForceInterval          = Mathf.Max(Mathf.RoundToInt(search.GetListSizeLimit() / (ulong)totalEnergy), 1);
        UpdateEnergyBars(healthForce, (int)currentForce, Color.blue);
        UpdateEnergyBars(healthExpandedBar, (int)currentEnergyExpanded, Color.yellow);
        gameObject.GetComponent <Renderer> ().material.color = agentColor;
    }
Ejemplo n.º 7
0
        public DistributedSearch(string configFilename)
        {
            // Grab the configuration info
            _configFilename = configFilename;
            var config = Toml.ReadFile <Configuration>(_configFilename);

            // Console.WriteLine("NumFeatures: " + config.Map.Features.Length);
            // foreach (var p in config.Map.Features)
            // {
            //     Console.WriteLine(p.Name);
            // }

            // Configuration for the search space
            _heroClass = CardReader.GetClassFromName(config.Deckspace.HeroClass);
            CardSet[] sets = CardReader.GetSetsFromNames(config.Deckspace.CardSets);
            _cardSet = CardReader.GetCards(_heroClass, sets);

            // Setup the logs to record the data on individuals
            InitLogs();

            // Set up search algorithm
            Console.WriteLine("Algo: " + config.Search.Type);
            if (config.Search.Type.Equals("MAP-Elites"))
            {
                var searchConfig = Toml.ReadFile <MapElitesParams>(config.Search.ConfigFilename);
                _searchAlgo = new MapElitesAlgorithm(searchConfig);
            }

            else if (config.Search.Type.Equals("EvolutionStrategy"))
            {
                var searchConfig = Toml.ReadFile <EvolutionStrategyParams>(config.Search.ConfigFilename);
                _searchAlgo = new EvolutionStrategyAlgorithm(searchConfig);
            }
        }
Ejemplo n.º 8
0
 void Start()
 {
     initCamera();
     grid                = new Grid(GRID_SIZE_X, GRID_SIZE_Y, NODE_SCALE, NODE_OUTLINE);
     algorithm           = new AStar(grid);
     speed               = GameSpeed.PAUSED;
     timeSinceLastUpdate = 0.0f;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// The algorithm to string.
        /// </summary>
        /// <param name="algorithm">
        /// The algorithm.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string AlgorithmToString(SearchAlgorithm algorithm)
        {
            if (algorithm == SearchAlgorithm.Retargeting)
            {
                return("У");
            }

            return(null);
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Get a list of vertices accessible from a given starting node
        /// </summary>
        /// <param name="startNode">The node from which to start the search</param>
        /// <param name="algorithm">The algorithm to use for discovering nodes, <see cref="SearchAlgorithm" /></param>
        /// <returns>List of vertices accessible from the given starting node</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Thrown if an invalid search algorithm is provided
        ///     <see cref="SearchAlgorithm" />
        /// </exception>
        public IEnumerable <Vertex <T> > DiscoverVertices(Vertex <T> startNode, SearchAlgorithm algorithm)
        {
            // use a HashSet for better performance, since we know that
            // no nodes should be marked as discovered more than once
            var visited = new HashSet <Vertex <T> > {
                startNode
            };

            // first node already discovered, return to user
            yield return(startNode);

            // add the starting node to the processing list
            var collection = new LinkedList <Vertex <T> >();

            collection.AddLast(startNode);

            while (collection.Count > 0)
            {
                Vertex <T> vertex;

                // take a vertex from the processing list
                switch (algorithm)
                {
                case SearchAlgorithm.DepthFirst:
                    vertex = collection.Last.ValueRef;
                    collection.RemoveLast();
                    break;

                case SearchAlgorithm.BreadthFirst:
                    vertex = collection.First.ValueRef;
                    collection.RemoveFirst();
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null);
                }

                // for each node attached to this node
                foreach (var child in vertex.GetNeighbours())
                {
                    // this node has already been processed, abort
                    if (visited.Contains(child))
                    {
                        continue;
                    }

                    // mark this child node as visited
                    visited.Add(child);

                    // add the child node to the queue for processing
                    collection.AddLast(child);

                    // return the found node to user
                    yield return(child);
                }
            }
        }
Ejemplo n.º 11
0
        public void StupidSearchTest()
        {
            SearchAlgorithm algorithm = new SearchAlgorithm();

            int[] numbers = new SimpleData().GetOrderedArray(1000);
            int   number  = 333;
            int   index   = algorithm.BinarySearch(numbers, number);

            Assert.AreEqual(333, index);
        }
Ejemplo n.º 12
0
        public void GivenAValueInTheArrayReturnsTheValue()
        {
            int searchValue, expectedFoundValue;

            searchValue = expectedFoundValue = 5;
            int[] myArray = new int[] { 1, 2, 3, 4, 5 };

            var foundValue = SearchAlgorithm.SequentialSearch(myArray, searchValue);

            Assert.Equal(foundValue, expectedFoundValue);
        }
Ejemplo n.º 13
0
    void Start()
    {
        Map map = GameObject.Find("Map").GetComponent <Map> ();

        // Get the cell size from the map.
        cellSize = map.cellSize;

        //Create the problem
        problem = new SokobanProblem(map.GetPlayerStart(), map.GetCrates(), map.GetGoals(), map.GetWalls());

        // Get the search algorithm to use
        Component[] all_algorithms = GetComponents <SearchAlgorithm> ();
        foreach (SearchAlgorithm alg in all_algorithms)
        {
            if (alg.isActiveAndEnabled)
            {
                search = alg;
            }
        }

        //set the problem in the search algorithm
        search.problem = problem;

        // checks if not in batchmode, if we and to load a solution and if a solution file exists
        if (!batchmode && tryLoad && File.Exists(solution))
        {
            loadPath();

            LOGGER.Log("Path Length: " + path.Count.ToString());
            LOGGER.Log("[{0}]", string.Join(",", path.ConvertAll <string> (Actions.ToString).ToArray()));
            // turn off search algorithm
            search.setRunning(false);
            search.setFinished(true);
        }


        //Get the crate objects
        crates = GameObject.FindGameObjectsWithTag("Crate");

        if (!batchmode)
        {
            LOGGER.Log("waiting on key !");
        }
        else
        {
            LOGGER.Log("running on batchmode to solve {0}\n{1}\n", map.map.name, map.map.text);
        }
        LOGGER.Flush();

        if (batchmode)
        {
            search.StartRunning();
        }
    }
Ejemplo n.º 14
0
 public void TestJourneyFromBuenosAiresViaCapeTownToCasablanca()
 {
     SearchAlgorithm.FindNextLeg(
         new Route[2] {
         new Route(CapeTown, 4),
         new Route(Casablanca, 3)
     },
         0,
         Casablanca,
         BuenosAires);
 }
        public static IAsyncSearchEngine <T> GetSearchEngine(SearchAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case SearchAlgorithm.Dijkstra:
                return(new AsyncDijkstraSearchEngine <T>());

            default:
                throw new ArgumentException();
            }
        }
Ejemplo n.º 16
0
    void Start()
    {
        // Get the cell size from the map.
        cellSize = GameObject.Find("Map").GetComponent <Map>().cellSize;

        // Get the search algorithm to use from the map
        search = GameObject.Find("Map").GetComponent <SearchAlgorithm> ();
        search.StartRunning();

        //Get the crate objects
        crates = GameObject.FindGameObjectsWithTag("Crate");
    }
Ejemplo n.º 17
0
        public void GivenAValueNotPresentInTheArrayReturnsMinusOne()
        {
            int searchValue, expectedFoundValue;

            searchValue        = 5;
            expectedFoundValue = -1;
            int[] myArray = new int[] { 1, 1, 1, 1, 1 };

            var foundValue = SearchAlgorithm.SequentialSearch(myArray, searchValue);

            Assert.Equal(foundValue, expectedFoundValue);
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Search(string searchAlgorithm, string queryText)
        {
            // Return these values to the view so that the view would not be reset after every search.
            ViewData["searchAlgorithm"] = searchAlgorithm;
            ViewData["queryText"]       = queryText;

            var posts = new List <Post>(await RssParser.ReadFeedsAsync());
            await HtmlParser.FetchPostContents(posts);

            SearchAlgorithm.FilterPosts(posts, queryText, searchAlgorithm);
            return(View(posts));
        }
Ejemplo n.º 19
0
 public void TestJourneyFromBuenosAiresViaCapeTownToNewYorkToLiverpoolToCasablanca()
 {
     Assert.IsTrue(SearchAlgorithm.FindNextLeg(
                       new Route[4] {
         new Route(CapeTown, 4),
         new Route(NewYork, 8),
         new Route(Liverpool, 4),
         new Route(Casablanca, 3)
     },
                       0,
                       Casablanca,
                       BuenosAires));
 }
 //Initializes Search
 public Search(Node[,] nodes, Node start, Node end, SearchAlgorithm searchAlgorithm)
 {
     //Set starting variables
     Start           = start;
     End             = end;
     SearchAlgorithm = searchAlgorithm;
     //Starting node should always be open, so add it to the OpenNodes list.
     OpenList.Add(start);
     //Set start node as in OpenNodes.
     start.InOpenNodes = true;
     //Apply Start F cost
     start.F = CalculateAStarH(start, end);
 }
Ejemplo n.º 21
0
 private void SearchButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         sa = this.SearchAlgorithmComboBox.SelectedIndex == 0 ? (SearchAlgorithm) new BidirectionalSearch() : new GreedySearch();
         sa.searchDidFinishedWithData = SearchDidFinishedWithData;
         sa.AsynchronousSearch(this.Graph, new Vertex(rootVertexChkbx.Text), new Vertex(goalVertexChkbx.Text));
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 22
0
        public static int IndexOf(byte[] data, int[] pattern, int startIndex = 0, SearchAlgorithm algorithm = SearchAlgorithm.BoyerMooreHorspool)
        {
            switch (algorithm)
            {
            case SearchAlgorithm.Naive:
                return(Naive.IndexOf(pattern, data, startIndex));

            case SearchAlgorithm.BoyerMooreHorspool:
                return(BoyerMooreHorspool.IndexOf(data, pattern, startIndex));

            default:
                throw new ArgumentException("Unknown Search Algorithm.", nameof(algorithm));
            }
        }
        public ShortestGraphPath ShortestPath(Node startNode, Node finishNode, SearchAlgorithm searchAlgorithm)
        {
            switch (searchAlgorithm)
            {
            case SearchAlgorithm.Dijkstra:
                return(GetShortestPathInternal <DijkstraAlgorithm>(startNode, finishNode));

            case SearchAlgorithm.AStar:
                return(GetShortestPathInternal <AStarAlgorithm>(startNode, finishNode));

            default:
                return(null);
            }
        }
Ejemplo n.º 24
0
        private void run_heuristics_sol(string ksProbelm)
        {
            Console.WriteLine("please choose search method: ");
            Console.WriteLine("1. Depth first search ");
            Console.WriteLine("2. Best first search ");

            int             searchMethod = get_input();
            SearchAlgorithm sa           = SearchAlgorithm.DepthFirstSearch;

            switch (searchMethod)
            {
            case 1:
                sa = SearchAlgorithm.DepthFirstSearch;
                break;

            case 2:
                sa = SearchAlgorithm.BestFirstSearch;
                break;

            default:
                Console.WriteLine("please enter a number between 1 to 2");
                break;
            }

            Console.WriteLine("please choose relaxation method: ");
            Console.WriteLine("1. Capacity ");
            Console.WriteLine("2. Integrality ");

            int relaxMethod       = get_input();
            NeglectedConstrain nc = NeglectedConstrain.Capacity;

            switch (relaxMethod)
            {
            case 1:
                nc = NeglectedConstrain.Capacity;
                break;

            case 2:
                nc = NeglectedConstrain.Integrality;
                break;

            default:
                Console.WriteLine("please enter a number between 1 to 2");
                break;
            }

            KsProblemHeuristic ksph = new KsProblemHeuristic(sa, nc);

            ksph.run_algorithm(ksProbelm + ".dat");
        }
Ejemplo n.º 25
0
    public SearchAlgorithm GetSearchAlgorithm()
    {
        Component[]     allAlgorithms        = GetComponents <SearchAlgorithm> ();
        SearchAlgorithm firstActiveAlgorithm = null;

        foreach (SearchAlgorithm alg in allAlgorithms)
        {
            if (alg.isActiveAndEnabled)
            {
                firstActiveAlgorithm = alg;
                break;
            }
        }
        return(firstActiveAlgorithm);
    }
        public override void PrintView()
        {
            var metricsPath =
                Path.Combine(Path.Combine(Simulation.Params.CurrentSimulationLoggerPath, @"algorithmMetrics.csv"));
            var algorithmsLogger = new Logger.Logger(new FileRecorder(Path.Combine(Path.Combine(Simulation.Params.CurrentSimulationLoggerPath, @"algorithms.csv"))));
            var dataSetLogger    = new Logger.Logger(new FileRecorder(Path.Combine(Simulation.Params.CurrentSimulationLoggerPath, @"algorithmsDataset.csv"), "DataModelId,CustomersNumber,VehicleNumber,MaxRideTimeDurationInMinutes,MaxAllowedUpperBoundLimitInMinutes,Seed"));
            var vehicleNumber    = 20;
            var count            = 0;

            //var algorithmsMetrics = new AlgorithmMetrics();
            Simulation.Params.VehicleNumber = vehicleNumber;
            for (int customersNumber = 25; customersNumber <= 100; customersNumber = customersNumber + 25)
            {
                Simulation.Params.NumberInitialRequests = customersNumber;
                for (int i = 0; i < 10; i++) // tests 10 different data models
                {
                    bool allowDropNodes = false;
                    RandomNumberGenerator.GenerateNewRandomSeed();
                    var dataModel     = DataModelFactory.Instance().CreateInitialSimulationDataModel(allowDropNodes, Simulation);
                    var printableList = dataModel.GetSettingsPrintableList();
                    ConsoleLogger.Log(printableList);
                    dataSetLogger.Log(dataModel.GetCSVSettingsMessage());
                    for (int searchTime = 5; searchTime <= 90; searchTime = searchTime + 5) //test different same datamodel with different search times
                    {
                        AlgorithmContainer algorithmContainer = new AlgorithmContainer();
                        foreach (var searchAlgorithm in algorithmContainer.SearchAlgorithms)
                        {
                            var algorithm = new SearchAlgorithm(searchAlgorithm, searchTime);
                            algorithm.Test(dataModel, allowDropNodes);
                            ConsoleLogger.Log(algorithm.GetResultPrintableList());

                            if (count == 0)
                            {
                                //logs base message type style
                                algorithmsLogger.Log(algorithm.GetCSVMessageStyle());
                            }
                            algorithmsLogger.Log(algorithm.GetCSVResultsMessage());
                            count++;
                        }
                    }
                }
            }

            //algorithmsMetrics.SaveMetrics(metricsPath);
        }
Ejemplo n.º 27
0
        public Email[] Get(string paramTwo, string paramOne, string APIKey)
        {
            if (!Permissions.ValidAPIKey(APIKey))
            {
                return new Email[] { }
            }
            ;


            Log.Append(String.Format("GET Email ({1}) - param: '{0}'", paramOne, paramTwo));

            if (paramOne.Contains("all="))
            {
                return(emailListRepository.GetAllEmails(paramTwo, paramOne).ToArray());
            }

            return(SearchAlgorithm.SearchDieNumber(paramOne).ToArray());
        }
Ejemplo n.º 28
0
        public void TestJourneyFromBuenosAiresViaCasablancaToLiverpool()
        {
            Assert.IsTrue(SearchAlgorithm.FindNextLeg(
                              new Route[2] {
                new Route(Casablanca, 5),
                new Route(Liverpool, 3)
            },
                              0,
                              Liverpool,
                              BuenosAires));

            Assert.AreEqual(8, SearchAlgorithm.FindNextLegDistance(
                                new Route[2] {
                new Route(Casablanca, 5),
                new Route(Liverpool, 3)
            },
                                0,
                                Liverpool,
                                BuenosAires));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Получает понятное имя элемента перечислителя.
        /// </summary>
        public static string GetName(this SearchAlgorithm searchAlgorithm)
        {
            switch (searchAlgorithm)
            {
            case SearchAlgorithm.Linear:
                return("Линейный");

            case SearchAlgorithm.Binary:
                return("Бинарный");

            case SearchAlgorithm.BinaryTree:
                return("Двоичное дерево");

            case SearchAlgorithm.HashTable:
                return("Хэш-таблица");

            default:
                return(null);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Run the provided search algorithm
        /// </summary>
        /// <param name="message"></param>
        /// <param name="search"></param>
        public static void RunSearch(string message, SearchAlgorithm search)
        {
            Console.WriteLine(message);

            // Time the search
            DateTime    start  = DateTime.Now;
            SudokuBoard sudoku = search();
            DateTime    end    = DateTime.Now;

            TimeSpan diff = end - start;

            if (sudoku != null)
            {
                Console.WriteLine("Solution found in " + diff.Hours + "h:" + diff.Minutes + "m:" + diff.Seconds + "s:" + diff.Milliseconds + "ms");
                sudoku.Display();
            }
            else
            {
                Console.WriteLine("No Solution Returned");
            }
        }
        public Element?[] Spell(string word, SearchAlgorithm algorithm)
        {
            Dictionary<int, Element> indexed = new Dictionary<int, Element>();
              word = Regex.Replace(word.ToLower(), "[^a-z\\s]", "");
              switch (algorithm)
              {
              case SearchAlgorithm.ElementBased:
            foreach (Element element in elements)
            {
              string symbol = element.Symbol.ToLower();
              if (word.Contains(symbol))
              {
            foreach (int i in word.IndexOfAll(symbol))
              indexed.Add(i, element);
            word = word.Replace(symbol, new string ('_', symbol.Length));
              }
            }
            break;

              case SearchAlgorithm.ChunkSearch:
            int maxElementLength = elements.Max(e => e.Symbol.Length);
            for (int searchLength = maxElementLength; searchLength > 0; searchLength--)
            {
              Element[] currentElements = elements.Where(e => e.Symbol.Length == searchLength).ToArray();
              for (int x = 0; x < word.Length - searchLength + 1; x++)
            foreach(Element currentElement in currentElements)
              if (word.Substring(x, searchLength) == currentElement.Symbol.ToLower())
              {
            indexed.Add(x, currentElement);
                ArrayList tmpList = new ArrayList(((ICollection)(Array)word.ToCharArray()));
                tmpList.SetRange(x, (ICollection)(Array)new string('_', searchLength).ToCharArray());
                word = new string(Array.ConvertAll(tmpList.ToArray(), item => (char)item));
              }
            }
            break;
              }
              List<Element?> spelled = new List<Element?>();
              int max = indexed.Max(item => item.Key);
              Element value;
              for (int i = 0; i <= max; i++)
              {
            if (indexed.TryGetValue(i, out value))
              spelled.Add(value);
            else if (word[i] == ' ')
              spelled.Add(null);
              }
              return spelled.ToArray();
        }
Ejemplo n.º 32
0
 private void SearchButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         sa = this.SearchAlgorithmComboBox.SelectedIndex == 0 ? (SearchAlgorithm) new BidirectionalSearch() : new GreedySearch();
         sa.searchDidFinishedWithData = SearchDidFinishedWithData;
         sa.AsynchronousSearch(this.Graph, new Vertex(rootVertexChkbx.Text), new Vertex(goalVertexChkbx.Text));
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 33
0
 public SearchParameters(PersonState startState, SearchAlgorithm algorithm)
 {
     StartState = startState;
     Algorithm = algorithm;
 }