当前位置: 首页>>代码示例>>C#>>正文


C# ISet.Where方法代码示例

本文整理汇总了C#中ISet.Where方法的典型用法代码示例。如果您正苦于以下问题:C# ISet.Where方法的具体用法?C# ISet.Where怎么用?C# ISet.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ISet的用法示例。


在下文中一共展示了ISet.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FindIndirectCircularReferences

        private static void FindIndirectCircularReferences(ISet<Node> childList)
        {
            var toIgnore = new HashSet<Node>();
            foreach (var node in childList.ToHashSet())
            {
                if(toIgnore.Contains(node))
                    continue;

                var path = new HashSet<Node>();
                if (IndirectlyDependsOnItself(node, node, ref path))
                {
                    path.Add(node);
                    toIgnore.UnionWith(path);
                    childList.ExceptWith(path);
                    var dependantOnCircularDependencies = childList.Where(x => path.Any(x.DependsOn));
                    var cirularHolder = new CircularDependencyHolderNode(path);
                    foreach (var dependantOnCircularDependency in dependantOnCircularDependencies)
                    {
                        //Remove all dependencies on nodes in the path
                        dependantOnCircularDependency.SiblingDependencies.RemoveWhere(x => path.Contains(x));
                        //Add dependency on circular holder
                        dependantOnCircularDependency.SiblingDependencies.Add(cirularHolder);
                    }
                    //Add all dependencies in the path to the new node
                    cirularHolder.SiblingDependencies.UnionWith(path.SiblingDependencies().Except(path)); //Should not be dependant on themselves
                    childList.Add(cirularHolder);
                }
            }
        }
开发者ID:davidkron,项目名称:DevArch,代码行数:29,代码来源:CircularReferenceFinder.cs

示例2: FindDirectCircularReferences

 private static void FindDirectCircularReferences(ISet<Node> childList1, ISet<Node> childList2)
 {
     while (true)
     {
         var circularRefs = new List<Tuple<Node, Node>>();
         foreach (var node in childList1)
         {
             foreach (var node2 in from node2 in childList2.Where(n => n != node) where node.SiblingDependencies.Contains(node2) where node2.SiblingDependencies.Contains(node) where circularRefs.All(x => x.Item1 != node2 && x.Item2 != node) select node2)
             {
                 circularRefs.Add(new Tuple<Node, Node>(node, node2));
             }
         }
         var circularDependencyHolders = new HashSet<Node>();
         //May need to check for circular references with the newly created CircularDependencyHolderNode?
         foreach (var circularRef in circularRefs)
         {
             var circularDependencyHolderNode = new CircularDependencyHolderNode(new List<Node> {circularRef.Item1, circularRef.Item2});
             circularDependencyHolderNode.SiblingDependencies.UnionWith(circularRef.Item1.SiblingDependencies.Union(circularRef.Item2.SiblingDependencies));
             childList2.Add(circularDependencyHolderNode);
             circularDependencyHolderNode.SiblingDependencies.Remove(circularRef.Item1);
             circularDependencyHolderNode.SiblingDependencies.Remove(circularRef.Item2);
             childList2.Remove(circularRef.Item1);
             childList2.Remove(circularRef.Item2);
             foreach (var node3 in childList2.Where(n => n != circularDependencyHolderNode))
             {
                 var containedNode1 = node3.SiblingDependencies.Contains(circularRef.Item1);
                 var containedNode2 = node3.SiblingDependencies.Contains(circularRef.Item2);
                 if (containedNode1 || containedNode2)
                     node3.SiblingDependencies.Add(circularDependencyHolderNode);
                 if (containedNode1)
                     node3.SiblingDependencies.Remove(circularRef.Item1);
                 if (containedNode2)
                     node3.SiblingDependencies.Remove(circularRef.Item2);
             }
             circularDependencyHolders.Add(circularDependencyHolderNode);
         }
         if (circularDependencyHolders.Any() && circularDependencyHolders != childList2)
             childList1 = circularDependencyHolders;
         else
             break;
     }
 }
开发者ID:davidkron,项目名称:DevArch,代码行数:42,代码来源:CircularReferenceFinder.cs

示例3: CPreOne

 public Solution CPreOne(ISet<int> target)
 {
     var retVal = new HashSet<int>();
     // Speaking in math: retVal += { cand \in V_0 | forall (v, v') \in E. v = cand => v' \in target }
     retVal.UnionWith(from cand in playerZeroNodes where edges.All(edge => edge.Item1 != cand || target.Contains(edge.Item2)) select cand);
     // Speaking in math: retVal += { cand \in V_1 | exists (v, v') \in E. v = cand && v' \in target }
     retVal.UnionWith(from cand in playerOneNodes where edges.Any(edge => edge.Item1 == cand && target.Contains(edge.Item2)) select cand);
     var tau = new PositionalStrategy();
     foreach(var p1Node in retVal.Where(node => IsPlayerOneNode(node)))
     {
         var targetEnumerator = target.Where(potentialTargetNode => GetSuccessors(p1Node).Contains(potentialTargetNode)).AsEnumerable().GetEnumerator();
         targetEnumerator.MoveNext();
         tau.Update(p1Node, targetEnumerator.Current);
     }
     return new Solution(retVal, tau);
 }
开发者ID:AutomataTutor,项目名称:automatatutor-backend,代码行数:16,代码来源:Arena.cs

示例4: GetDefinitionsOfSymbol

 /// <summary>
 /// Returns the definitions for the specified symbol.
 /// </summary>
 /// <param name="symbol">Symbol</param>
 /// <param name="definitions">SymbolDefinitions</param>
 /// <returns>SymbolDefinitions</returns>
 private ISet<SymbolDefinition> GetDefinitionsOfSymbol(ISymbol symbol,
     ISet<SymbolDefinition> definitions)
 {
     var resolvedDefinitions = new HashSet<SymbolDefinition>();
     resolvedDefinitions.UnionWith(definitions.Where(
         val => val.Symbol.Equals(symbol)));
     return resolvedDefinitions;
 }
开发者ID:yonglehou,项目名称:PSharp,代码行数:14,代码来源:DataFlowInfo.cs

示例5: ReplaceWithInSolutionReference

        void ReplaceWithInSolutionReference(ISet<EquatableEdge<IBuilder>> graph, IEnumerable<ISlnProjectBuilder> childProjectBuilders, SuiteReferenceBuilder dep)
        {
            var inSolutionRef = inSolutionReferenceBuilderFactory.CreateInSolutionReferenceBuilder(dep.ReferencedProject);
            inSolutionRef.Reference = dep.Reference;

            foreach (var builder in childProjectBuilders)
            {
                builder.RemovePrerequisite(dep);

                var edgesToModify = new HashSet<EquatableEdge<IBuilder>>(graph.Where(edge => edge.Source == builder && edge.Target == dep));
                RemoveEdges(graph, edgesToModify);

                foreach (var edge in edgesToModify)
                {
                    var newEdge = new EquatableEdge<IBuilder>(edge.Source, inSolutionRef);
                    AddEdge(graph, newEdge);
                }
            }
        }
开发者ID:vigoo,项目名称:bari,代码行数:19,代码来源:OptimizingBuildContextFactory.cs

示例6: RemoveEdgesWhereSourceIs

 void RemoveEdgesWhereSourceIs(ISet<EquatableEdge<IBuilder>> graph, IBuilder source)
 {
     var toRemove = new HashSet<EquatableEdge<IBuilder>>(graph.Where(edge => edge.Source == source));
     RemoveEdges(graph, toRemove);
 }
开发者ID:vigoo,项目名称:bari,代码行数:5,代码来源:OptimizingBuildContextFactory.cs

示例7: MergeSolutionBuilds

        private bool MergeSolutionBuilds(ISet<EquatableEdge<IBuilder>> graph)
        {
            log.Debug("### Merging solution builds");

            // Searching for [MSBuildRunner] -> [SlnBuilder] -> [ISlnProjectBuilder*] patterns
            var patterns =
                graph
                    .Where(edge => edge.Source is MSBuildRunner && edge.Target is SlnBuilder)
                    .ToDictionary(
                        edge => (SlnBuilder)edge.Target,
                        edge => new SolutionBuildPattern(graph, (MSBuildRunner)edge.Source, (SlnBuilder)edge.Target));

            foreach (var edge in graph)
            {
                if (edge.Source is SlnBuilder && edge.Target is ISlnProjectBuilder)
                {
                    SolutionBuildPattern pattern;
                    if (patterns.TryGetValue((SlnBuilder)edge.Source, out pattern))
                    {
                        var targetBuilder = (ISlnProjectBuilder)edge.Target;
                        pattern.ProjectBuilders.Add(targetBuilder);
                        pattern.Projects.Add(targetBuilder.Project);
                    }
                }
            }

            // Finding involved modules
            var modules = new HashSet<Module>();
            var projects = new HashSet<Project>();

            foreach (var pattern in patterns.Values)
            {
                foreach (var prj in pattern.ProjectBuilders)
                {
                    projects.Add(prj.Project);
                    modules.Add(prj.Project.Module);
                }
            }

            // Creating merge plan
            foreach (var module in modules)
            {
                bool testsCovered = module.TestProjects.Any() && module.TestProjects.All(projects.Contains);
                bool covered = module.Projects.Any() && module.Projects.All(projects.Contains);

                if (covered)
                {
                    log.DebugFormat("Merging project builders of module {0} into a single solution", module.Name);
                    MergeProjects(graph, patterns, module.Projects.ToArray(), module.Name);
                }

                if (testsCovered)
                {
                    log.DebugFormat("Merging test project builders of module {0} into a single solution", module.Name);
                    MergeProjects(graph, patterns, module.TestProjects.Cast<Project>().ToArray(), module.Name + " tests");
                }
            }

            return true;
        }
开发者ID:vigoo,项目名称:bari,代码行数:60,代码来源:OptimizingBuildContextFactory.cs

示例8: CutRedundantSolutionBuilds

        private bool CutRedundantSolutionBuilds(ISet<EquatableEdge<IBuilder>> graph)
        {
            log.Debug("### Cutting redundant solution builds");

            var slnBuilders = new HashSet<SlnBuilder>(graph.Select(edge => edge.Target).OfType<SlnBuilder>());
            var rootBuilderMap = graph
                .Where(edge => edge.Source is MSBuildRunner && slnBuilders.Contains(edge.Target))
                .ToDictionary(edge => (SlnBuilder)edge.Target, edge => FindSolutionRootBuilder(graph, edge));

            if (slnBuilders.Any())
            {
                foreach (var slnBuilder in slnBuilders)
                {
                    if (rootBuilderMap.ContainsKey(slnBuilder))
                    {
                        var projectSet = new HashSet<Project>(slnBuilder.Projects);
                        var childProjectBuilders = new HashSet<ISlnProjectBuilder>(slnBuilder
                            .Prerequisites
                            .OfType<ISlnProjectBuilder>());

                        foreach (var projectBuilder in childProjectBuilders)
                        {
                            foreach (var dep in projectBuilder.Prerequisites.OfType<SuiteReferenceBuilder>().ToList())
                            {
                                if (dep.Reference.Type == ReferenceType.Build &&
                                    projectSet.Contains(dep.ReferencedProject))
                                {
                                    log.DebugFormat(
                                        "Project {0}'s reference {1} can be replaced to in-solution-reference in {2}",
                                        projectBuilder.Project, dep, slnBuilder);

                                    // All sln project builders belonging to `slnBuilder` must replace their reference to dep to a
                                    // new in solution reference builder (both in the builder and in the graph)
                                    ReplaceWithInSolutionReference(graph, childProjectBuilders, dep);

                                    // All edges from dep must be removed and a single new edge to the MSBuild runner belonging to this `slnBuilder` added
                                    RemoveEdgesWhereSourceIs(graph, dep);

                                    var newEdge = new EquatableEdge<IBuilder>(dep, rootBuilderMap[slnBuilder]);
                                    AddEdge(graph, newEdge);
                                }
                            }
                        }
                    }
                }
            }

            return true;
        }
开发者ID:vigoo,项目名称:bari,代码行数:49,代码来源:OptimizingBuildContextFactory.cs

示例9: GenerateProductModels

        private Dictionary<Model.Product, ICollection<string>> GenerateProductModels(ISet<Model.ProductType> types)
        {
            Dictionary<Model.Product, ICollection<string>> models =
                new Dictionary<Model.Product, ICollection<string>>();

            foreach (Product product in this.products)
            {
                ObjectId typeId = types.Where(t => t.Name == product.Type).Select(t => t.Id).First();

                Model.Product currentProduct = new Model.Product(
                    product.Name,
                    product.Description,
                    product.ProductCode,
                    product.Price,
                    product.Quantity,
                    typeId,
                    product.CategoryIds);

                models.Add(currentProduct, product.Shops);
            }

            return models;
        }
开发者ID:freemsly,项目名称:DataBases,代码行数:23,代码来源:MongoProductImporter.cs

示例10: AnnotateAndRename_WorkerAsync

            // The rename process and annotation for the bookkeeping is performed in one-step
            private async Task<Solution> AnnotateAndRename_WorkerAsync(
                Solution originalSolution,
                Solution partiallyRenamedSolution,
                HashSet<DocumentId> documentIdsToRename,
                ISet<RenameLocation> renameLocations,
                RenamedSpansTracker renameSpansTracker,
                bool replacementTextValid)
            {
                try
                {
                    foreach (var documentId in documentIdsToRename.ToList())
                    {
                        _cancellationToken.ThrowIfCancellationRequested();

                        var document = originalSolution.GetDocument(documentId);
                        var semanticModel = await document.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
                        var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(_cancellationToken).ConfigureAwait(false);

                        // Get all rename locations for the current document.
                        var allTextSpansInSingleSourceTree = renameLocations
                            .Where(l => l.DocumentId == documentId && ShouldIncludeLocation(renameLocations, l))
                            .ToDictionary(l => l.Location.SourceSpan);

                        // All textspan in the document documentId, that requires rename in String or Comment
                        var stringAndCommentTextSpansInSingleSourceTree = renameLocations
                            .Where(l => l.DocumentId == documentId && l.IsRenameInStringOrComment)
                            .GroupBy(l => l.ContainingLocationForStringOrComment)
                            .Select(g => g.Key)
                            .ToSet();

                        var conflictLocationSpans = _conflictLocations
                                                    .Where(t => t.DocumentId == documentId)
                                                    .Select(t => t.ComplexifiedSpan).ToSet();

                        // Annotate all nodes with a RenameLocation annotations to record old locations & old referenced symbols.
                        // Also annotate nodes that should get complexified (nodes for rename locations + conflict locations)
                        var parameters = new RenameRewriterParameters(
                            _renamedSymbolDeclarationAnnotation,
                            document,
                            semanticModel,
                            originalSyntaxRoot,
                            _replacementText,
                            _originalText,
                            _possibleNameConflicts,
                            allTextSpansInSingleSourceTree,
                            stringAndCommentTextSpansInSingleSourceTree,
                            conflictLocationSpans,
                            originalSolution,
                            _renameLocationSet.Symbol,
                            replacementTextValid,
                            renameSpansTracker,
                            _optionSet,
                            _renameAnnotations,
                            _cancellationToken);

                        var renameRewriterLanguageService = document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
                        var newRoot = renameRewriterLanguageService.AnnotateAndRename(parameters);

                        if (newRoot == originalSyntaxRoot)
                        {
                            // Update the list for the current phase, some files with strings containing the original or replacement
                            // text may have been filtered out.
                            documentIdsToRename.Remove(documentId);
                        }
                        else
                        {
                            partiallyRenamedSolution = partiallyRenamedSolution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
                        }
                    }

                    return partiallyRenamedSolution;
                }
                catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
                {
                    throw ExceptionUtilities.Unreachable;
                }
            }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:78,代码来源:ConflictResolver.Session.cs

示例11: BuildCompilationsAsync

        private Task BuildCompilationsAsync(
            Solution solution,
            ProjectId initialProject,
            ISet<ProjectId> projectsToBuild,
            CancellationToken cancellationToken)
        {
            var allProjectIds = new List<ProjectId>();
            if (initialProject != null)
            {
                allProjectIds.Add(initialProject);
            }

            allProjectIds.AddRange(projectsToBuild.Where(p => p != initialProject));

            var logger = Logger.LogBlock(FunctionId.BackgroundCompiler_BuildCompilationsAsync, cancellationToken);

            var compilationTasks = allProjectIds.Select(solution.GetProject).Where(p => p != null).Select(p => p.GetCompilationAsync(cancellationToken)).ToArray();
            return Task.WhenAll(compilationTasks).SafeContinueWith(t =>
                {
                    logger.Dispose();
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        lock (_buildGate)
                        {
                            if (!cancellationToken.IsCancellationRequested)
                            {
                                _mostRecentCompilations = t.Result;
                            }
                        }
                    }
                },
                CancellationToken.None,
                TaskContinuationOptions.None,
                TaskScheduler.Default);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:35,代码来源:BackgroundCompiler.cs

示例12: ModuloNewSetIntoMultiDictionary

 /// <summary>
 /// Inserts a set into a dictionary, such that all set entries are keys that point to the set. If, however, 
 /// the dictionary contains keys already that match any of the inserted keys, then any entries in the sets these keys 
 /// point to, will also be added to the set, and those entries will also point to the new set.
 /// If the following conditions hold before executing the method, they will also hold afterwards:
 ///     - every key in the dictionary will point to a set that contains itself and possible other keys,
 ///     - every key will exist in only one of the value sets of the dictionary.
 /// </summary>
 /// <param name="listOfAllAliases">A dictionary of sets (every key maps to a set)</param>
 /// <param name="foundAliases">A set that will be inserted</param>
 private static void ModuloNewSetIntoMultiDictionary(IDictionary<string, ISet<string>> listOfAllAliases, ISet<string> foundAliases)
 {
     var listOfOtherAliasSets = foundAliases
                                 .Where(alias => listOfAllAliases.ContainsKey(alias))
                                 .Select(alias => listOfAllAliases[alias])
                                 .Distinct()
                                 .ToList();      // modifying foundAliases is not allowed without ToList()
     foreach (ISet<string> otherAliasSet in listOfOtherAliasSets)
         foundAliases.UnionWith(otherAliasSet);
     foreach (string alias in foundAliases)
         listOfAllAliases[alias] = foundAliases;
 }
开发者ID:paluno,项目名称:GitHistoryAnalyzer,代码行数:22,代码来源:AliasFinder.cs

示例13: LayOutSiblingNodes

        public static List<Node> LayOutSiblingNodes(ISet<Node> toBeGrouped)
        {
            if (toBeGrouped.Count <= 1)
                return toBeGrouped.ToList();
            var groupedNodes = new List<Node>();
            var hasBeenAdded = new HashSet<Node>();
            var nextGroupTarget = toBeGrouped;

            //Remove nodes that does not depend on anything and is never referenced
            var unreferenced = toBeGrouped.Where(x => !x.SiblingDependencies.Any()
                                                       && !toBeGrouped.SiblingDependencies().Contains(x)).ToHashSet();
            nextGroupTarget.ExceptWith(unreferenced);
            while (toBeGrouped.Any())
            {
                if (!nextGroupTarget.Any())
                {
                    nextGroupTarget = toBeGrouped;
                }
                while (nextGroupTarget.Any())
                {
                    var currentLayer = GetFacadeNodes(nextGroupTarget);
                    nextGroupTarget = currentLayer.SiblingDependencies().ToHashSet();
                    if (nextGroupTarget.Any())
                    {
                        //Get the next layer to check if any of the dependencies are unique to a node of the current layer
                        var nextLayer = GetFacadeNodes(nextGroupTarget);

                        //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique
                        var leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer));
                        nextLayer.RemoveAll(x => leftForNextBatch.SiblingDependencies().Contains(x));

                        var uniqueDependencies =
                            nextLayer.Where(x => !currentLayer.All(n => n.SiblingDependencies.Contains(x)))
                                .Distinct()
                                .ToList();

                        //If there are unique dependencies, vertical layers are created to separate the unique dependency from layers that dont depend on it
                        if (uniqueDependencies.Any())
                        {
                            while (true)
                            {
                                //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique
                                leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer));
                                nextLayer.RemoveAll(x => leftForNextBatch.Any(y => y.IndirectlyDependsOn(x)));
                                var groupsToCreate = FindDependencyPatterns(currentLayer, nextLayer);
                                var toBeShared = new HashSet<Node>();
                                toBeGrouped.ExceptWith(currentLayer);

                                foreach (var dependencyGroup in groupsToCreate)
                                {
                                    var referencers = dependencyGroup.Referencers;
                                    currentLayer.RemoveRange(referencers.ToList());
                                    var dependants = dependencyGroup.Dependants.ToList();
                                    nextGroupTarget.ExceptWith(dependants);
                                    toBeGrouped.ExceptWith(dependants);
                                    hasBeenAdded.UnionWith(dependants);
                                    hasBeenAdded.UnionWith(referencers);
                                    // Add dependant to the vertical layer
                                    var depNode = CreateHorizontalLayer(dependants);
                                    // Add references to the vertical layer
                                    var referenceNode = CreateHorizontalLayer(referencers);
                                    var newList = new List<Node> {depNode, referenceNode};
                                    //Get ALL the possible candidates for the vertical layer
                                    var verticalCandidates =
                                        referencers.SelectMany(x => x.IndirectSiblingDependencies())
                                            .Except(dependants)
                                            .Union(
                                                dependants.SelectMany(x => x.IndirectSiblingDependencies()))
                                            .Distinct()
                                            .Except(hasBeenAdded).Intersect(toBeGrouped)
                                            .ToHashSet();

                                    //Get all the nodes in this current call depth
                                    var otherGroups = groupsToCreate.Except(dependencyGroup);
                                    var nodesInOtherGroups = otherGroups.
                                        SelectMany(x => x.Dependants.Union(x.Referencers)).ToHashSet();
                                    var otherNodes =
                                        toBeGrouped.Union(currentLayer)
                                            .Union(nodesInOtherGroups)
                                            .Except(verticalCandidates)
                                            .ToHashSet();

                                    var siblingDepsRelevantForNewNode = new HashSet<Node>();
                                    //If any of the other nodes depends on the vertical candidate the candidate is removed and will be placed in a later iteration of this call (it is still left in toBeGrouped)
                                    foreach (var candidate in verticalCandidates.ToList())
                                    {
                                        var otherNodesDependantOnCandidate =
                                            otherNodes.Where(x => x.IndirectlyDependsOn(candidate)).ToHashSet();
                                        if (toBeShared.Contains(candidate) || otherNodesDependantOnCandidate.Any())
                                        {
                                            verticalCandidates.Remove(candidate);
                                            toBeShared.Add(candidate);
                                        }
                                    }

                                    if (verticalCandidates.Any())
                                    {
                                        toBeGrouped.ExceptWith(verticalCandidates);
                                        nextGroupTarget.ExceptWith(verticalCandidates);
                                        hasBeenAdded.UnionWith(verticalCandidates);
//.........这里部分代码省略.........
开发者ID:davidkron,项目名称:DevArch,代码行数:101,代码来源:SiblingReorderer.cs

示例14: GetFacadeNodes

 public static List<Node> GetFacadeNodes(ISet<Node> targets)
 {
     if(!targets.Any())
         return new List<Node>();
     var allDependencies = targets.SiblingDependencies().ToList();
     var noOneDependantOn =  targets.Where(n => !allDependencies.Contains(n)).ToList();
     if (noOneDependantOn.Any())
         return noOneDependantOn;
     var indirectDepsCount = targets.ToDictionary(x => x, x => x.IndirectSiblingDependencies().Count());
     var maxDeps = indirectDepsCount.Values.Max();
     return targets.Where(x => indirectDepsCount[x] == maxDeps).ToList();
 }
开发者ID:davidkron,项目名称:DevArch,代码行数:12,代码来源:SiblingReorderer.cs

示例15: LadderLength

    public int LadderLength(string beginWord, string endWord, ISet<string> wordDict) {
		if (beginWord == endWord) return 1;
		wordDict.Remove(beginWord);
		wordDict.Remove(endWord);
		var words = new [] { beginWord, endWord }.Concat(wordDict.Where(word => word.Length == beginWord.Length)).Select((word, i) => new { Word = word, Index = i }).ToList();
		
		var paths = new List<int>[words.Count];
		for (var i = 0; i < paths.Length; ++i)
		{
			paths[i] = new List<int>();
		}
		for (var i = 0; i < beginWord.Length; ++i)
		{
            var hashMap = new Hashtable();
            foreach (var item in words)
            {
                var newWord = string.Format("{0}_{1}", item.Word.Substring(0, i), item.Word.Substring(i + 1));
				List<int> similars;
                if (!hashMap.ContainsKey(newWord))
				{
					similars = new List<int>();
					hashMap.Add(newWord, similars);
				}
				else
				{
					similars = (List<int>)hashMap[newWord];
				}
				foreach (var similar in similars)
				{
					paths[similar].Add(item.Index);
					paths[item.Index].Add(similar);
				}
                similars.Add(item.Index);
            }
		}
		
		var left = words.Count - 1;
		var lastRound = new List<int> { 0 };
		var visited = new bool[words.Count];
		visited[0] = true;
		for (var result = 2; left > 0; ++result)
		{
			var thisRound = new List<int>();
			foreach (var index in lastRound)
			{
				foreach (var next in paths[index])
				{
					if (!visited[next])
					{
						visited[next] = true;
						if (next == 1) return result;
						thisRound.Add(next);
					}
				}
			}
            if (thisRound.Count == 0) break;
			lastRound = thisRound;
		}
		
		return 0;
    }
开发者ID:alexguo88,项目名称:LeetCode,代码行数:61,代码来源:127.WordLadder.cs


注:本文中的ISet.Where方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。