コード例 #1
0
ファイル: Program.cs プロジェクト: qwert11/mojo
        public static void Parce(IConnectionStringBuilder conn, ICPath path)
        {
            List <AD>   listAD       = new List <AD>();
            IDataParser paserProduct = new ParcerProduct(listAD);

            paserProduct.SetConnection(conn);
            paserProduct.Select(path);
            HashSet <AD> distinctAD = new HashSet <AD>(listAD, new SameADComparer());

            ADMapper     mapper       = new ADMapper(Directory.GetCurrentDirectory() + "\\storage.xml");
            HashSet <AD> storedListAD = new HashSet <AD>(new SameADComparer());

            foreach (AD o in mapper.ReadAll())
            {
                storedListAD.Add(o);
            }

            distinctAD = new HashSet <AD>(distinctAD.Except(storedListAD, new SameADComparer()), new SameADComparer());

            if (storedListAD.SequenceEqual(storedListAD.Union(distinctAD, new SameADComparer()), new SameADComparer()) == false)
            {
//				ShowBalloon("Новые товары", GetShortInfoAD(distinctAD, 3));
                foreach (AD ad in distinctAD)
                {
                    Console.WriteLine(ad);
                }
                listAD = storedListAD.Union(distinctAD).ToList();
                mapper.WriteAll(listAD);
            }
        }
コード例 #2
0
ファイル: GameLogic.cs プロジェクト: GoogleJump/ZeroG
    public static HashSet <Node> GetPossibleMoves(int player)
    {
        Node           currentLocation   = GamePosition.Players[player].getLocation();
        HashSet <Node> possibleLocations = new HashSet <Node>();
        HashSet <Node> occupiedLocations = GameLogic.getAllOtherPlayerLocations(GamePosition.Players[player]);
        HashSet <Node> checkLocations;

        if (playerHasEnoughTickets(GamePosition.Players[player], TransportType.blackCard))
        {
            checkLocations = currentLocation.getAllEdges();
            checkLocations.ExceptWith(occupiedLocations);
            possibleLocations.Union(checkLocations);
        }
        else
        {
            foreach (TransportType type in Enum.GetValues(typeof(TransportType)))
            {
                if (playerHasEnoughTickets(GamePosition.Players[player], type))
                {
                    checkLocations = currentLocation.getEdges(type);
                    checkLocations.ExceptWith(occupiedLocations);
                    possibleLocations.Union(checkLocations);
                }
            }
        }
        return(possibleLocations);
    }
コード例 #3
0
        private void ResultWindowName_Loaded(object sender, RoutedEventArgs e)
        {
            // remove quotes, if checked
            if (RemoveCharQuotes)
            {
                ListBoxA = ListBoxA.Replace("\'", "").Replace("\"", "");
                ListBoxB = ListBoxB.Replace("\'", "").Replace("\"", "");
            }

            // remove custom chars
            if (CustomCharsToRemove != null)
            {
                foreach (var item in CustomCharsToRemove)
                {
                    ListBoxA = ListBoxA.Replace(item.ToString(), "");
                    ListBoxB = ListBoxB.Replace(item.ToString(), "");
                }
            }

            // set labels
            LabelA.Content     = NameBoxA;
            LabelB.Content     = NameBoxB;
            LabelOnlyA.Content = "Only " + NameBoxA;
            LabelOnlyB.Content = "Only " + NameBoxB;
            LabelAOrB.Content  = NameBoxA + " OR " + NameBoxB;
            LabelAAndB.Content = NameBoxA + " AND " + NameBoxB;

            // make HashSet out of lists
            var hashSetA = new HashSet <string>();
            var hashSetB = new HashSet <string>();

            AddListToHashSet(ListBoxA, hashSetA, TrimWhitespace);
            AddListToHashSet(ListBoxB, hashSetB, TrimWhitespace);

            //Restate lists
            TextBoxListA.Text = string.Join("\n", hashSetA);
            TextBoxListB.Text = string.Join("\n", hashSetB);

            LabelCountRestateA.Content = hashSetA.Count;
            LabelCountRestateB.Content = hashSetB.Count;

            //Only lists
            TextBoxOnlyA.Text = string.Join("\n", hashSetA.Except(hashSetB));
            TextBoxOnlyB.Text = string.Join("\n", hashSetB.Except(hashSetA));

            LabelCountOnlyA.Content = hashSetA.Except(hashSetB).Count();
            LabelCountOnlyB.Content = hashSetB.Except(hashSetA).Count();

            //And list
            TextBoxAAndB.Text = string.Join("\n", hashSetA.Intersect(hashSetB));

            LabelCountAAndB.Content = hashSetA.Intersect(hashSetB).Count();

            //Or list
            TextBoxAOrB.Text = string.Join("\n", hashSetA.Union(hashSetB));

            LabelCountAOrB.Content = hashSetA.Union(hashSetB).Count();
        }
コード例 #4
0
        // Return the additional set of constants to keep
        HashSet <string> FindMin(PersistentProgram inprog, HashSet <string> candidates, Dictionary <string, int> constantToPerfDelta, ref int perf)
        {
            var iter       = 1;
            var assignment = new HashSet <string>();
            var additional = new HashSet <string>();

            candidates = new HashSet <string>(candidates);

            while (candidates.Count != 0)
            {
                Console.WriteLine("------ ITER {0} -------", iter++);

                // Drop one and re-run
                var c = PickRandom(candidates);
                candidates.Remove(c);

                Console.WriteLine("  >> Trying {0}", c);

                int inlined = perf;
                var rt      = PruneAndRun(inprog, candidates.Union(keep), out assignment, ref inlined);

                if (rt == BoogieVerify.ReturnStatus.OK)
                {
                    // dropping was fine
                    Console.WriteLine("  >> Dropping it and {0} others", (candidates.Count + keep.Count - assignment.Count));
                    constantToPerfDelta.Add(c, (inlined - perf));

                    // MustKeep is a subset of assignment, if no user annotation is given.
                    // Under user annotations, mustkeep is really "should keep"
                    //Debug.Assert(mustkeep.IsSubsetOf(assignment));
                    keep.IntersectWith(assignment);

                    dropped.Add(c);
                    dropped.UnionWith(candidates.Union(keep).Difference(assignment));

                    candidates = assignment;
                    candidates.ExceptWith(keep);

                    perf = inlined;

                    Debug.Assert(!candidates.Contains(c));
                }
                else
                {
                    Console.WriteLine("  >> Cannot drop");
                    keep.Add(c);
                    additional.Add(c);
                }

                //Log(iter);
                Console.WriteLine("Time elapsed: {0} sec", sw.Elapsed.TotalSeconds.ToString("F2"));
            }

            return(additional.Intersection(keep));
        }
コード例 #5
0
ファイル: Day09.cs プロジェクト: ryanclarke/AdventOfCode
    public static void Run()
    {
        var input = File
                    .ReadAllLines("../../../input/09.txt")
                    .SelectMany((l, y) => l.Select((c, x) => (new Point(x, y), int.Parse(c.ToString()))))
                    .ToDictionary(l => l.Item1, l => l.Item2);

        var neighbors = new List <Point>()
        {
            new Point(-1, 0),
            new Point(1, 0),
            new Point(0, -1),
            new Point(0, 1)
        };
        var lowPoints = input
                        .Where(l => neighbors
                               .Select(p => p + l.Key)
                               .Where(input.ContainsKey)
                               .All(p => input[p] > l.Value))
                        .ToList();;

        lowPoints
        .Sum(l => l.Value + 1)
        .Dump("09a (594): ");

        lowPoints.Select(l => Area(l.Key))
        .OrderByDescending(x => x)
        .Take(3)
        .Aggregate(1, (a, x) => a * x)
        .Dump("09b (858494): ");


        int Area(Point p)
        {
            var ps = new HashSet <Point> {
                p
            };
            var ns = new HashSet <Point>();

            do
            {
                ps = ps.Union(ns).ToHashSet();
                ns = ps.SelectMany(x => neighbors
                                   .Select(n => n + x)
                                   .Where(input.ContainsKey)
                                   .Where(x => input[x] != 9))
                     .ToHashSet();
            } while (ps.Union(ns).Count() > ps.Count);

            return(ps.Count);
        };
    }
コード例 #6
0
ファイル: Min.cs プロジェクト: zvonimir/corral
        // Minimize
        public static HashSet <int> FindMin(HashSet <int> templatesAlreadyDropped, out Dictionary <int, int> templateToPerfDelta)
        {
            templateToPerfDelta = new Dictionary <int, int>();

            var iter      = 1;
            var tokeep    = new HashSet <int>();
            var templates = new HashSet <int>(templateMap.Keys);

            templates.ExceptWith(templatesAlreadyDropped);
            AssignDefaultCost(templates);

            while (templates.Count != 0)
            {
                Console.WriteLine("------ ITER {0} -------", iter++);

                // Drop one and re-run
                var c = PickRandom(templates);

                templates.Remove(c);

                Console.WriteLine("  >> Trying {0} :: {1}", c, templateToStr[c]);

                Dictionary <string, int> perf;
                HashSet <string>         filesVerified;
                string fileFailed;

                var rt = PruneAndRun(templates.Union(tokeep), out perf, out filesVerified, out fileFailed);

                if (rt == BoogieVerify.ReturnStatus.OK)
                {
                    // dropping was fine
                    Console.WriteLine("  >> Files verified: {0}", filesVerified.Concat(" "));
                    Console.WriteLine("  >> Dropping it");

                    // TODO: maintain information of extra constants that are
                    // no longer provable, and prune templateMap accordingly

                    // Extra information
                    var delta = 0;
                    perf.Iter(tup => delta += (tup.Value - fileToPerf[tup.Key]));
                    templateToPerfDelta[c]  = delta;

                    // Update perf stats
                    perf.Iter(tup => fileToPerf[tup.Key] = tup.Value);
                }
                else
                {
                    Debug.Assert(fileFailed != null);
                    Console.WriteLine("  >> Files verified: {0}", filesVerified.Concat(" "));
                    Console.WriteLine("  >> File failed: {0}", fileFailed);
                    Console.WriteLine("  >> Cannot drop");
                    tokeep.Add(c);
                }

                //Log(iter);
                Console.WriteLine("Time elapsed: {0} sec", sw.Elapsed.TotalSeconds.ToString("F2"));
            }

            return(tokeep);
        }
コード例 #7
0
        public static double JackardCoef(string str1, string str2, int n)
        {
            HashSet <string> gramms1 = new HashSet <string>();
            HashSet <string> gramms2 = new HashSet <string>();

            for (int i = 0; i <= str1.Length - n; i++)
            {
                string buffer = str1.Substring(i, n);
                gramms1.Add(buffer);
            }

            for (int i = 0; i <= str2.Length - n; i++)
            {
                string buffer = str2.Substring(i, n);
                gramms2.Add(buffer);
            }

            int    common    = gramms1.Union(gramms2).Count();
            int    intersect = gramms2.Intersect(gramms1).Count();
            double coef      = 0;

            if (common != 0)
            {
                coef = (double)intersect / (double)common;
            }
            return(coef);
        }
コード例 #8
0
ファイル: DependencyVisitor.cs プロジェクト: liyistc/symdiff
        private void AddTaintedOutputs(Procedure node)
        {
            if (!this.outputTaints.ContainsKey(node))
            {
                return;
            }

            var taintedVars   = new HashSet <Variable>(this.outputTaints[node].Select(kv => kv.Key));
            var buTaintedVars = new HashSet <Variable>(this.allDeps[node]
                                                       .Where(x => x.Value.Contains(Dependency.Utils.VariableUtils.BottomUpTaintVar))
                                                       .Select(x => x.Key));



            AddSummaryChangedAnnotations(node, buTaintedVars);

            taintedVars = new HashSet <Variable>(taintedVars.Union(buTaintedVars));
            var untaintedVars = node.OutParams.Union(node.Modifies.Select(x => x.Decl)).Where(x => !taintedVars.Contains(x));

            var untaintedNames = untaintedVars.Select(x => x.Name)
                                 .ToList <object>();

            var ens = new Ensures(true, Expr.True);

            ens.Attributes = new QKeyValue(Token.NoToken, "out_ntainted", untaintedNames, null);
            node.Ensures.Add(ens);
        }
コード例 #9
0
        public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable <ProjectId> projectIds, IEnumerable <DocumentId> documentIds)
        {
            lock (this.gate)
            {
                var coordinator = default(WorkCoordinator);
                if (!this.documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator))
                {
                    throw new ArgumentException("workspace");
                }

                // no specific projects or documents provided
                if (projectIds == null && documentIds == null)
                {
                    coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet());
                    return;
                }

                // specific documents provided
                if (projectIds == null)
                {
                    coordinator.Reanalyze(analyzer, documentIds.ToSet());
                    return;
                }

                var solution = workspace.CurrentSolution;
                var set      = new HashSet <DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable <DocumentId>());
                set.Union(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds));

                coordinator.Reanalyze(analyzer, set);
            }
        }
コード例 #10
0
    static void Main(string[] args)
    {
        var first = new HashSet <Item>()
        {
            new Item()
            {
                Name = "a"
            },
            new Item()
            {
                Name = "b"
            },
        };
        var second = new HashSet <Item>()
        {
            new Item()
            {
                Name = "b"
            },
            new Item()
            {
                Name = "c"
            },
        };
        var both = first.Union(second).ToList();

        both.ForEach(Console.WriteLine);
        Console.ReadKey();
    }
コード例 #11
0
 public RelationshipDictionaryTests()
 {
     _firstToOneAttr = new HasOneAttribute
     {
         PublicName = "firstToOne",
         LeftType   = typeof(Dummy),
         RightType  = typeof(ToOne),
         Property   = typeof(Dummy).GetProperty(nameof(Dummy.FirstToOne))
     };
     _secondToOneAttr = new HasOneAttribute
     {
         PublicName = "secondToOne",
         LeftType   = typeof(Dummy),
         RightType  = typeof(ToOne),
         Property   = typeof(Dummy).GetProperty(nameof(Dummy.SecondToOne))
     };
     _toManyAttr = new HasManyAttribute
     {
         PublicName = "toManies",
         LeftType   = typeof(Dummy),
         RightType  = typeof(ToMany),
         Property   = typeof(Dummy).GetProperty(nameof(Dummy.ToManies))
     };
     _relationships.Add(_firstToOneAttr, _firstToOnesResources);
     _relationships.Add(_secondToOneAttr, _secondToOnesResources);
     _relationships.Add(_toManyAttr, _toManiesResources);
     _allResources = new HashSet <Dummy>(_firstToOnesResources.Union(_secondToOnesResources).Union(_toManiesResources).Union(_noRelationshipsResources));
 }
コード例 #12
0
ファイル: MinHash.cs プロジェクト: ErichL/DocumentID
        // Calculates the similarity of two minhashes
        public double Similarity(List <uint> l1, List <uint> l2)
        {
            HashSet <uint> hs1 = new HashSet <uint>(l1);
            HashSet <uint> hs2 = new HashSet <uint>(l2);

            return((double)hs1.Intersect(hs2).Count() / (double)hs1.Union(hs2).Count());
        }
コード例 #13
0
        static void Main(string[] args)
        {
            string     s    = "42,12";
            List <int> list = new List <int>()
            {
                4, 4, 5, 61, 1
            };
            List <int> list2 = new List <int>()
            {
                1, 4, 5, 1, 8
            };
            HashSet <int>       set  = new HashSet <int>(list);
            HashSet <int>       set2 = new HashSet <int>(list2);
            ConcurrentBag <int> bag  = new ConcurrentBag <int>(list2);
            var e = set.Union(bag);

            Console.WriteLine(bag.Count(1));
            Console.WriteLine("Hello Extension Methods!");
            Console.WriteLine(list.IncludesAll(list2));
            Console.WriteLine(list.NotEmpty());
            var temp = list.SelectOcl(e => e > 4);

            Console.WriteLine(temp.Count);
            temp.Println();
        }
コード例 #14
0
ファイル: RomanNumeralParser.cs プロジェクト: Animarr/Animarr
        public static HashSet <ArabicRomanNumeral> GetArabicRomanNumeralsMapping(int upToArabicNumber = DICTIONARY_PREPOPULATION_SIZE)
        {
            if (upToArabicNumber == DICTIONARY_PREPOPULATION_SIZE)
            {
                return(new HashSet <ArabicRomanNumeral>(_arabicRomanNumeralsMapping.Take(upToArabicNumber)));
            }

            if (upToArabicNumber < DICTIONARY_PREPOPULATION_SIZE)
            {
                return
                    ((HashSet <ArabicRomanNumeral>) new HashSet <ArabicRomanNumeral>(_arabicRomanNumeralsMapping).Take(upToArabicNumber));
            }

            if (upToArabicNumber >= DICTIONARY_PREPOPULATION_SIZE)
            {
                if (_arabicRomanNumeralsMapping.Count >= upToArabicNumber)
                {
                    return(new HashSet <ArabicRomanNumeral>(_arabicRomanNumeralsMapping.Take(upToArabicNumber)));
                }

                HashSet <ArabicRomanNumeral> largerMapping = GenerateAdditionalMappings(DICTIONARY_PREPOPULATION_SIZE + 1, upToArabicNumber);
                _arabicRomanNumeralsMapping = (HashSet <ArabicRomanNumeral>)_arabicRomanNumeralsMapping.Union(largerMapping);
            }

            return(_arabicRomanNumeralsMapping);
        }
コード例 #15
0
    internal static HashSet <Char> GetVariables(Expressions exp)
    {
        HashSet <Char> variables = GetVariablesFromString(exp.Left);

        variables.Union(GetVariablesFromString(exp.Right));
        return(variables);
    }
コード例 #16
0
ファイル: RegionController.cs プロジェクト: abshev/SSBPD
        private VersusRegionViewModel getViewModel(IEnumerable <int> regionOneValues, IEnumerable <int> regionTwoValues)
        {
            var regionOneValuesSet = new HashSet <int>(regionOneValues);
            var regionTwoValuesSet = new HashSet <int>(regionTwoValues);
            var regionPlayers      = from p in db.Players
                                     where p.RegionValue != null && (regionOneValuesSet.Union(regionTwoValuesSet).Contains(p.RegionValue.Value))
                                     orderby p.ELO descending
                                     select p;
            var regionOnePlayerIds = new HashSet <int>(regionPlayers.Where(p => regionOneValuesSet.Contains(p.RegionValue.Value)).Select <Player, int>(p => p.PlayerId));
            var regionTwoPlayerIds = new HashSet <int>(regionPlayers.Where(p => regionTwoValuesSet.Contains(p.RegionValue.Value)).Select <Player, int>(p => p.PlayerId));

            var sets = from s in db.Sets
                       where (regionOnePlayerIds.Contains(s.WinnerID) && regionTwoPlayerIds.Contains(s.LoserID)) ||
                       (regionOnePlayerIds.Contains(s.LoserID) && regionTwoPlayerIds.Contains(s.WinnerID))
                       select s;

            int regionOneWins    = sets.Where(s => !s.isDraw && regionOnePlayerIds.Contains(s.WinnerID)).Count();
            int regionTwoWins    = sets.Where(s => !s.isDraw && regionOnePlayerIds.Contains(s.LoserID)).Count();
            int draws            = sets.Where(s => s.isDraw).Count();
            var regionOnePlayers = from p in regionPlayers
                                   where regionOnePlayerIds.Contains(p.PlayerId)
                                   select p;

            var regionTwoPlayers = from p in regionPlayers
                                   where regionTwoPlayerIds.Contains(p.PlayerId)
                                   select p;
            var regionOneList = regionOneValues.Select(rv => (Region)rv);
            var regionTwoList = regionTwoValues.Select(rv => (Region)rv);

            return(new VersusRegionViewModel(regionOneList, regionTwoList, regionOneWins, regionTwoWins, draws, regionOnePlayers, regionTwoPlayers, sets));
        }
コード例 #17
0
        public bool Invalidate(ImmutableArray <IPythonModule> analysisDependencies, int analysisVersion, out ImmutableArray <AnalysisModuleKey> dependencies)
        {
            dependencies = ImmutableArray <AnalysisModuleKey> .Empty;
            IPythonModule module;
            int           version;

            lock (_syncObj) {
                if (_analysisVersion >= analysisVersion)
                {
                    return(false);
                }

                version = _analysisVersion;
                module  = _module;
            }

            var dependenciesHashSet = new HashSet <AnalysisModuleKey>();

            foreach (var dependency in analysisDependencies.ExcludeDefault().Where(d => d.ModuleType != ModuleType.Specialized))
            {
                if (!dependency.Equals(module) &&
                    (dependency.ModuleType == ModuleType.User && dependency.Analysis.Version < version || dependency.Analysis is EmptyAnalysis))
                {
                    dependenciesHashSet.Add(new AnalysisModuleKey(dependency));
                }
            }

            if (dependenciesHashSet.Count == 0)
            {
                return(false);
            }

            lock (_syncObj) {
                if (_analysisVersion >= analysisVersion)
                {
                    return(false);
                }

                if (_analysisDependencies == null)
                {
                    _analysisDependencies = dependenciesHashSet;
                }
                else
                {
                    var countBefore = _analysisDependencies.Count;
                    _analysisDependencies.UnionWith(dependenciesHashSet);
                    if (countBefore == _analysisDependencies.Count)
                    {
                        return(false);
                    }
                }

                UpdateAnalysisTcs(analysisVersion);
                dependencies = _parserDependencies != null
                    ? ImmutableArray <AnalysisModuleKey> .Create(_parserDependencies.Union(_analysisDependencies).ToArray())
                    : ImmutableArray <AnalysisModuleKey> .Create(_analysisDependencies);

                return(true);
            }
        }
コード例 #18
0
        public bool Invalidate(IPythonModule module, PythonAst ast, int bufferVersion, int analysisVersion, out ImmutableArray <AnalysisModuleKey> dependencies)
        {
            dependencies = ImmutableArray <AnalysisModuleKey> .Empty;
            if (_bufferVersion >= bufferVersion)
            {
                return(false);
            }

            var dependenciesHashSet = FindDependencies(module, ast, bufferVersion);

            lock (_syncObj) {
                if (_analysisVersion >= analysisVersion && _bufferVersion >= bufferVersion)
                {
                    return(false);
                }

                _ast                = ast;
                _module             = module;
                _moduleType         = module.ModuleType;
                _parserDependencies = dependenciesHashSet;

                Interlocked.Exchange(ref _bufferVersion, bufferVersion);
                UpdateAnalysisTcs(analysisVersion);
                dependencies = _analysisDependencies != null
                    ? ImmutableArray <AnalysisModuleKey> .Create(_parserDependencies.Union(_analysisDependencies).ToArray())
                    : ImmutableArray <AnalysisModuleKey> .Create(_parserDependencies);

                return(true);
            }
        }
コード例 #19
0
 public RelationshipDictionaryTests()
 {
     FirstToOneAttr = new HasOneAttribute("first-to-one")
     {
         PrincipalType            = typeof(Dummy),
         DependentType            = typeof(ToOne),
         InternalRelationshipName = "FirstToOne"
     };
     SecondToOneAttr = new HasOneAttribute("second-to-one")
     {
         PrincipalType            = typeof(Dummy),
         DependentType            = typeof(ToOne),
         InternalRelationshipName = "SecondToOne"
     };
     ToManyAttr = new HasManyAttribute("to-manies")
     {
         PrincipalType            = typeof(Dummy),
         DependentType            = typeof(ToMany),
         InternalRelationshipName = "ToManies"
     };
     Relationships.Add(FirstToOneAttr, FirstToOnesEntities);
     Relationships.Add(SecondToOneAttr, SecondToOnesEntities);
     Relationships.Add(ToManyAttr, ToManiesEntities);
     AllEntities = new HashSet <Dummy>(FirstToOnesEntities.Union(SecondToOnesEntities).Union(ToManiesEntities).Union(NoRelationshipsEntities));
 }
コード例 #20
0
        /// <summary>
        /// 聯集
        /// </summary>
        static public string UnionListString(this string it, string src, char delimitSymbol)
        {
            HashSet <string> set1 = new HashSet <string>(it.Split(delimitSymbol));
            HashSet <string> set2 = new HashSet <string>(src.Split(delimitSymbol));

            return(set1.Union(set2).ToListString(delimitSymbol));
        }
コード例 #21
0
 public RelationshipDictionaryTests()
 {
     FirstToOneAttr = new HasOneAttribute("firstToOne")
     {
         LeftType     = typeof(Dummy),
         RightType    = typeof(ToOne),
         PropertyInfo = typeof(Dummy).GetProperty(nameof(Dummy.FirstToOne))
     };
     SecondToOneAttr = new HasOneAttribute("secondToOne")
     {
         LeftType     = typeof(Dummy),
         RightType    = typeof(ToOne),
         PropertyInfo = typeof(Dummy).GetProperty(nameof(Dummy.SecondToOne))
     };
     ToManyAttr = new HasManyAttribute("toManies")
     {
         LeftType     = typeof(Dummy),
         RightType    = typeof(ToMany),
         PropertyInfo = typeof(Dummy).GetProperty(nameof(Dummy.ToManies))
     };
     Relationships.Add(FirstToOneAttr, FirstToOnesEntities);
     Relationships.Add(SecondToOneAttr, SecondToOnesEntities);
     Relationships.Add(ToManyAttr, ToManiesEntities);
     AllEntities = new HashSet <Dummy>(FirstToOnesEntities.Union(SecondToOnesEntities).Union(ToManiesEntities).Union(NoRelationshipsEntities));
 }
コード例 #22
0
        internal void AddTargetObjects(object[] targetsToAdd, Vector2 pos)
        {
            if (targetsToAdd == null)
            {
                Log.Error("No targets to add.");
                return;
            }

            // filter null targets
            var newTargets = targetsToAdd.Where(x => !Util.IsBadRef(x));

            if (targetObjects == null)
            {
                SetTargetObjects(newTargets);
                return;
            }

            // allow user to abort if the node-count exceeds the limit
            var combined = targetObjects.Union(newTargets).ToHashSet();

            if (!UserAcceptsTargetCount(combined.Count()))
            {
                return;
            }

            targetObjects = combined;
            var entitiesToAdd = MakeAssignableEntities(newTargets, selectedBackendType);

            workspace.AddTargets(entitiesToAdd.ToArray(), pos);
            UpdateBackend();
        }
コード例 #23
0
ファイル: DAG.cs プロジェクト: sjas/DataDebug
        private bool traversalHasLoop(AST.Address current_addr, Dictionary <AST.Address, AST.Address> visited, AST.Address from_addr)
        {
            // base case 1: loop check
            if (visited.ContainsKey(current_addr))
            {
                return(true);
            }
            // base case 2: an input cell
            if (!_formulas.ContainsKey(current_addr))
            {
                return(false);
            }
            // recursive case (it's a formula)
            // check both single inputs and the inputs of any vector inputs
            bool OK = true;
            HashSet <AST.Address> single_inputs = _f2i[current_addr];
            HashSet <AST.Address> vector_inputs = new HashSet <AST.Address>(_f2v[current_addr].SelectMany(addrs => addrs.Addresses()));

            foreach (AST.Address input_addr in vector_inputs.Union(single_inputs))
            {
                if (OK)
                {
                    // new dict to mark visit
                    var visited2 = new Dictionary <AST.Address, AST.Address>(visited);
                    // mark visit
                    visited2.Add(current_addr, from_addr);
                    // recurse
                    OK = OK && !traversalHasLoop(input_addr, visited2, from_addr);
                }
            }
            return(!OK);
        }
コード例 #24
0
        public HashSetTester()
        {
            HashSet <string> employees = new HashSet <string>(new string[] { "Fred", "Bert", "Harry", "John" });
            HashSet <string> customers = new HashSet <string>(new string[] { "John", "Sid", "Harry", "Diana" });

            employees.Add("James");
            customers.Add("Francesca");
            Console.WriteLine("Employees:");
            foreach (string name in employees)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine("\nCustomers:");
            foreach (string name in customers)
            {
                Console.WriteLine(name);
            }
            //Console.WriteLine("\nCustomers who are also employees:");
            //customers.IntersectWith(employees);
            //foreach (string name in customers)
            //{
            //    Console.WriteLine(name);
            //}
            Console.WriteLine("\nCustomers union employees:");
            IEnumerable <string> cu = customers.Union(employees);

            foreach (string name in cu)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine($"Is subset {customers.IsSubsetOf(employees)}");
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: born2drive/Dot-Net-Course
        static void Main(string[] args)
        {
            int[] array1 = new int[] { 1, 2, 3, 4, 5, 6, 7 };

            int[] array2 = new int[] { 4, 5, 7, 6, 8, 9, 10 };

            int[] array3 = new int[] { 6, 7, 8, 9, 10 };


            HashSet <int> hash1 = new HashSet <int>(array1);
            HashSet <int> hash2 = new HashSet <int>(array2);
            HashSet <int> hash3 = new HashSet <int>(array3);

            //int[] intersectResult = hash1.Intersect(hash2).ToArray();

            //foreach (var item in intersectResult)
            //{
            //    Console.Write(item + " ");
            //}
            //Console.WriteLine();


            int[] unionResult = hash1.Union(hash3).ToArray();

            foreach (var item in unionResult)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }
コード例 #26
0
        public static int unionSize(List <int> ls1, List <int> ls2)
        {
            HashSet <int> hs1 = new HashSet <int>(ls1);
            HashSet <int> hs2 = new HashSet <int>(ls2);

            return(hs1.Union(hs2).Count());
        }
コード例 #27
0
        public CSG(HashSet <string> NTS, Alphabet TS, string S, Rules rules)
        {
            this.NTS   = NTS;
            this.TS    = TS;
            this.S     = S;
            this.rules = rules;
            if (NTS.Intersect(TS).Count() > 0)
            {
                throw new ArgumentException("NTS and TS must be disjoint!");
            }
            if (!NTS.Contains(S))
            {
                throw new ArgumentException("S must be contained in NTS!");
            }
            if (rules.Keys.Any(rs => TS.IsSupersetOf(rs.Symbols)))
            {
                throw new ArgumentException($"Left-hand side of all rules must contain NTS!");
            }
            var  allSymbols = new HashSet <string>(NTS.Union(TS));
            bool x          = rules.Any(r => !allSymbols.IsSupersetOf(r.Key.Symbols));
            bool y          = rules.Any(r => r.Value.Any(rs => !rs[0].Equals("") && !allSymbols.IsSupersetOf(rs.Symbols)));

            if (rules.Any(r => !allSymbols.IsSupersetOf(r.Key.Symbols) || r.Value.Any(rs => !rs[0].Equals("") && !allSymbols.IsSupersetOf(rs.Symbols))))
            {
                throw new ArgumentException($"Rules can not contain symbols that are neither NTS nor TS!");
            }
        }
コード例 #28
0
        public int Run(IRDMPPlatformRepositoryServiceLocator repositoryLocator, IDataLoadEventListener listener, ICheckNotifier checkNotifier, GracefulCancellationToken token)
        {
            // if we have no listener use a throw immediately one (generate exceptions if it went badly)
            if (listener == null)
            {
                listener = new ThrowImmediatelyDataLoadEventListener();
            }

            // whatever happens we want a listener to record the worst result for the return code (even if theres ignore all errors listeners being used)
            var toMemory = new ToMemoryDataLoadEventListener(false);

            // User might have some additional listeners registered
            listener = new ForkDataLoadEventListener(AdditionalListeners.Union(new [] { toMemory, listener }).ToArray());

            // build the engine and run it
            var engine = UseCase.GetEngine(Pipeline, listener);

            engine.ExecutePipeline(token ?? new GracefulCancellationToken());

            // return code of -1 if it went badly otherwise 0
            var exitCode = toMemory.GetWorst() >= ProgressEventType.Error ? -1:0;

            if (exitCode == 0)
            {
                PipelineExecutionFinishedsuccessfully?.Invoke(this, new PipelineEngineEventArgs(engine));
            }

            return(exitCode);
        }
コード例 #29
0
ファイル: Node.cs プロジェクト: l2obin/Dynamo
        protected override Expression compileBody(
            Dictionary <INode, string> symbols,
            Dictionary <INode, List <INode> > letEntries,
            HashSet <string> initializedIds,
            HashSet <string> conditionalIds)
        {
            var testBranch = arguments[_test].compile(symbols, letEntries, initializedIds, conditionalIds);

            var trueSet  = new HashSet <string>(initializedIds);
            var falseSet = new HashSet <string>(initializedIds);

            var trueCond  = new HashSet <string>(conditionalIds);
            var falseCond = new HashSet <string>(conditionalIds);

            var trueBranch  = arguments[_true].compile(symbols, letEntries, trueSet, trueCond);
            var falseBranch = arguments[_false].compile(symbols, letEntries, falseSet, falseCond);

            var alwaysInitialized = trueSet.Intersect(falseSet).ToList();

            conditionalIds.UnionWith(trueCond.Union(falseCond));
            conditionalIds.UnionWith(trueSet.Union(falseSet).Except(alwaysInitialized));

            initializedIds.UnionWith(alwaysInitialized);

            return(Expression.NewIf(testBranch, trueBranch, falseBranch));
        }
コード例 #30
0
        private void SetMultiValuedProperty <T, V>(MultiValuedProperty <T> inputValues, MultiValuedProperty <V> existingValues, SetOrganizationConfig.Resolver <T, V> resolver)
        {
            if (inputValues == null)
            {
                existingValues.Clear();
                return;
            }
            if (!inputValues.IsChangesOnlyCopy)
            {
                existingValues.Clear();
                using (IEnumerator <V> enumerator = resolver(inputValues).Distinct <V>().GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        V item = enumerator.Current;
                        existingValues.Add(item);
                    }
                    return;
                }
            }
            HashSet <V>     first   = new HashSet <V>(existingValues);
            IEnumerable <V> second  = resolver(inputValues.Added.Cast <T>());
            IEnumerable <V> second2 = resolver(inputValues.Removed.Cast <T>());

            existingValues.Clear();
            foreach (V item2 in first.Union(second).Except(second2))
            {
                existingValues.Add(item2);
            }
        }
コード例 #31
0
        public string Generate(Board _board, GameUnit _unit, GameUnit _finishUnit)
        {
            var stringBuilder = new StringBuilder();
            var words = MagicWordsStore.Words
                                       .Concat(SpecialWords)
                                       .ToArray();
            var usedUnits = new HashSet<GameUnit>();
            while (!_unit.Equals(_finishUnit))
            {
                if (TimeLimiter.NeedStop())
                    break;

                foreach (var powerWord in words.OrderByDescending(x => x.Length))
                {
                    if (TimeLimiter.NeedStop())
                        break;

                    var newlyUsedUnits = new HashSet<GameUnit>();
                    var currentUnit = _unit;
                    var fail = false;
                    for (var i = 0; i < powerWord.Length; ++i)
                    {
                        var command = powerWord[i];
                        newlyUsedUnits.Add(currentUnit);
                        var nextUnit = currentUnit.MakeStep(CommandConverter.Convert(command));
                        var locked = !_board.IsValid(nextUnit);
                        if (newlyUsedUnits.Contains(nextUnit) ||
                            usedUnits.Contains(nextUnit) ||
                            (locked && i < powerWord.Length - 1) ||
                            (locked && !nextUnit.Equals(_finishUnit)))
                        {
                            fail = true;
                            break;
                        }
                        if (!locked)
                        {
                            currentUnit = nextUnit;
                        }
                    }
                    var allUsedUnits = new HashSet<GameUnit>(usedUnits.Union(newlyUsedUnits));
                    if (!fail && ReachableStatesGetter.CanReach(_board, currentUnit, false, allUsedUnits, _finishUnit))
                    {
                        _unit = currentUnit;
                        usedUnits = allUsedUnits;
                        stringBuilder.Append(powerWord);
                        break;
                    }
                }
            }
            foreach (var command in Enum.GetValues(typeof(Command)).Cast<Command>().Except(new[] { Command.Empty }))
            {
                if (!_board.IsValid(_unit.MakeStep(command)))
                {
                    stringBuilder.Append(CommandConverter.CovertToAnyChar(command));
                    break;
                }
            }
            return stringBuilder.ToString();
        }
コード例 #32
0
ファイル: NPMIEngine.cs プロジェクト: hyunjong-lee/yes64
        public static double simularity(HashSet<string> setA, HashSet<string> setB)
        {
            double interCount = setA.Intersect(setB).Count();
            if (interCount == 0) return 0;

            double unionCount = setA.Union(setB).Count();
            return interCount / unionCount;
        }
コード例 #33
0
        public static Type ResolveControllerType(string areaName, string controllerName)
        {
            // controller type to find and return
            Type controllerType;

            // is the type cached?
            var cacheKey = areaName + "_" + controllerName;
            if (cache.TryGetValue(cacheKey, out controllerType))
                return cache[cacheKey];

            lock (syncLock)
            {
                if (cache.TryGetValue(cacheKey, out controllerType))
                    return controllerType;

                // find controller details
                IEnumerable<string> areaNamespaces = FindNamespacesForArea(areaName, RouteTable.Routes);

                var area = areaName;
                var controller = controllerName;
                var controllerBuilder = ControllerBuilder.Current;

                // Find controller type
                HashSet<string> namespaces = null;
                if (areaNamespaces != null)
                {
                    areaNamespaces = (from ns in areaNamespaces
                                      where ns != "Elmah.Mvc"
                                      select ns).ToList();
                    if (areaNamespaces.Any())
                    {
                        namespaces = new HashSet<string>(areaNamespaces, StringComparer.OrdinalIgnoreCase);
                        if (string.IsNullOrEmpty(areaName))
                        {
                            namespaces = new HashSet<string>(
                                namespaces.Union(controllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase),
                                StringComparer.OrdinalIgnoreCase
                            );
                        }
                    }
                }
                else if (controllerBuilder.DefaultNamespaces.Count > 0)
                {
                    namespaces = controllerBuilder.DefaultNamespaces;
                }
                controllerType = GetControllerTypeWithinNamespaces(area, controller, namespaces);

                // Cache the result
                cache.Add(cacheKey, controllerType);

                // Return
                return controllerType;
            }
        }
コード例 #34
0
        public static void Main(string[] args)
        {
            HashSet<int> first = new HashSet<int>();
            first.Add(1);
            first.Add(2);
            first.Add(3);

            Console.Write("First set: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            HashSet<int> second = new HashSet<int>();
            second.Add(4);
            second.Add(1);
            second.Remove(1);

            Console.Write("Second set: ");
            foreach (var item in second)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            first.Union(second);

            Console.Write("Sets union: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            //second.Add(1);

            first.Intersect(second);

            Console.Write("Sets intersection: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();
        }
コード例 #35
0
        public static void Main()
        {
            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();
            firstSet.Add(1);
            firstSet.Add(2);
            firstSet.Add(7);
            secondSet.Add(7);
            secondSet.Add(13);
            secondSet.Add(19);
            firstSet.Remove(2);

            var unionSet = firstSet.Union(secondSet);
            Console.WriteLine("Union set = {0}", unionSet);

            var intersectSet = firstSet.Intersect(secondSet);
            Console.WriteLine("Intersect set = {0}", intersectSet);
        }
コード例 #36
0
        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();

            hashSet.Add("ooo");
            hashSet.Add("qqq");
            hashSet.Add("ppp");
            hashSet.Add("iii");

            foreach (var item in hashSet.Items)
            {
                Console.WriteLine(item);
            }

            hashSet.Remove("iii");
            Console.WriteLine("\nCount after removal: {0}", hashSet.Count);


            Console.WriteLine();
            Console.WriteLine(hashSet.Find("ppp"));


            HashSet<string> secondHashSet = new HashSet<string>();
            secondHashSet.Add("www");
            secondHashSet.Add("qqq");
            secondHashSet.Add("yyy");
            secondHashSet.Add("ooo");

            Console.WriteLine("\nUnion: ");
            HashSet<string> union = hashSet.Union(secondHashSet);
            foreach (var item in union.Items)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\nIntersection: ");
            HashSet<string> intersection = hashSet.Intersect(secondHashSet);
            foreach (var item in intersection.Items)
            {
                Console.WriteLine(item);
            }
        }
コード例 #37
0
ファイル: SubsetSum.cs プロジェクト: jbondhus/Subset-Sum
 // Needs sorted data!
 private static HashSet<List<int>> findSubsetIndices(int sum, int[] data)
 {
     HashSet<List<int>> results = new HashSet<List<int>>();
     int tsum = sum;
     List<int> indicies = new List<int>();
     for (int i = data.Length - 1; i >= 0; --i)
     {
         if (data[i] <= tsum)
         {
             tsum -= data[i];
             indicies.Add(i);
         }
         if (tsum == 0)
         {
             results = new HashSet<List<int>>(results.Union(findSubsetIndices(sum, data, indicies)));
             i = indicies.ElementAt(0);
             indicies = new List<int>();
             tsum = sum;
         }
     }
     return results;
 }
コード例 #38
0
ファイル: Program.cs プロジェクト: giorgosrevis/C-Homeworks
        static void Main(string[] args)
        {
            int NewNumber = 10000000;

            int[] FirstArray = new int[NewNumber];

            int[] SecondArray = new int[NewNumber];

            int[] ThirdArray = new int[NewNumber];

            FirstArray[0] = 1;

            SecondArray[0] = 2;

            ThirdArray[0] = 2;

            for (int i = 1; i < NewNumber; i++)
            {
                FirstArray[i] = 2 * FirstArray[i - 1] + 3;
                SecondArray[i] = 3 * SecondArray[i - 1] + 1;
                ThirdArray[i] = 2 * ThirdArray[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(FirstArray);

            HashSet<int> hash2 = new HashSet<int>(SecondArray);

            HashSet<int> hash3 = new HashSet<int>(ThirdArray);

            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2));

            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }
        }
コード例 #39
0
        static void Main(string[] args)
        {
            int number = 100000;

           
            int[] arr1 = new int[number];
            int[] arr2 = new int[number];
            int[] arr3 = new int[number];

            arr1[0] = 1;
            arr2[0] = 2;
            arr3[0] = 2;

            for (int i = 1; i < number; i++)
            {
                arr1[i] = 2 * arr1[i - 1] + 3;
                arr2[i] = 3 * arr2[i - 1] + 1;
                arr3[i] = 2 * arr3[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(arr1);
            HashSet<int> hash2 = new HashSet<int>(arr2);
            HashSet<int> hash3 = new HashSet<int>(arr3);
            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2)); 
            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));


        

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }


        }
コード例 #40
0
ファイル: Program.cs プロジェクト: madoxxs/Materials
        static void Main(string[] args)
        {
            Console.WriteLine("molq vavedete K ot klaviaturata:");
            int k = int.Parse(Console.ReadLine());
            if (k < 16)
            {
                int[] moni1 = new int[k];
                moni1[0] = 1;
                for (int i = 1; i < k; i++)
                {
                    moni1[i] = 2 * moni1[i - 1] + 3;
                }
                HashSet<int> example = new HashSet<int>(moni1);
                int[] moni2 = new int[k];
                moni2[0] = 2;
                for (int i = 1; i < k; i++)
                {
                    moni2[i] = 3 * moni1[i - 1] + 1;
                }
                HashSet<int> example1 = new HashSet<int>(moni2);
                int[] moni3 = new int[k];
                moni2[0] = 2;
                for (int i = 1; i < k; i++)
                {
                    moni2[i] = 2 * moni1[i - 1] - 1;
                }
                HashSet<int> example2 = new HashSet<int>(moni2);

                int[] intersectResult = example.Intersect(example1).ToArray();
                int[] intersectResult1 = example.Intersect(example2).ToArray();
                int[] intersectResult2 = example1.Intersect(example2).ToArray();
                int[] intersectResult3 = example.Intersect(example1.Intersect(example2)).ToArray();
                int[] unionResult = example.Union(example1).ToArray();
                int[] unionResult1 = example.Union(example2).ToArray();
                int[] unionResult2 = example1.Union(example2).ToArray();
                int[] unionResult3 = example.Union(example1.Union(example2)).ToArray();

                foreach (var item in intersectResult)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult1)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult2)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult3)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult1)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult2)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult3)
                {
                    Console.Write(item + " ");
                }

                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("molq vavedete chislo po-malko ot 16");
            }
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: vaster/Telerik.vasko
        static void Main(string[] args)
        {
            IHashSet<int> sampleOne = new HashSet<int>();
           
            sampleOne.Add(1);
            sampleOne.Add(1);
            sampleOne.Add(2);
            sampleOne.Add(3);
            sampleOne.Add(4);
            sampleOne.Add(5);
            sampleOne.Add(6);
            sampleOne.Add(7);
            sampleOne.Add(8);
            sampleOne.Add(9);

             IHashSet<int> sampleTwo = new HashSet<int>();

            sampleTwo.Add(1);
            sampleTwo.Add(2);
            sampleTwo.Add(9);
            sampleTwo.Add(100);


            Console.WriteLine("sampleOne:");
            foreach (var item in sampleOne)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("sampleTwo:");
            foreach (var item in sampleTwo)
            {
                Console.WriteLine(item);
            }


            IHashSet<int> intersected = sampleOne.Intersect(sampleTwo);

            Console.WriteLine("Intesected of sampleOne and sampleTwo:");
            foreach (var item in intersected)
            {
                Console.WriteLine(item);
            }

            IHashSet<int> union = sampleOne.Union(sampleTwo);

            Console.WriteLine("Union of sampleOne and sampleTwo:");
            foreach (var item in union)
            {
                Console.WriteLine(item);
            }

            int founded = sampleOne.Find(1);
            Console.WriteLine("Look for '1':" + founded);

            Console.WriteLine("Count:" + sampleOne.Count);
            sampleOne.Remove(3);
            sampleOne.Clear();
            Console.WriteLine("Count after clear:" + sampleOne.Count);

        }
コード例 #42
0
ファイル: GameLogic.cs プロジェクト: GoogleJump/ZeroG
    public HashSet<Node> GetPossibleMoves(int player, GamePosition gamePosition)
    {
        Node currentLocation = gamePosition.Players[player].getLocation();
        HashSet<Node> possibleLocations = new HashSet<Node>();
        HashSet<Node> occupiedLocations = getAllOtherPlayerLocations(gamePosition.Players[player]);
        HashSet<Node> checkLocations;

        if(playerHasEnoughTickets(gamePosition.Players[player], TransportType.blackCard)){
            checkLocations = currentLocation.getAllEdges();
            checkLocations.ExceptWith(occupiedLocations);
            possibleLocations = new HashSet<Node>(possibleLocations.Union(checkLocations));
        } else {
            foreach(TransportType type in Enum.GetValues(typeof(TransportType))){
                if(playerHasEnoughTickets(gamePosition.Players[player], type)){
                    checkLocations = currentLocation.getEdges(type);
                    checkLocations.ExceptWith(occupiedLocations);
                    possibleLocations = new HashSet<Node>(possibleLocations.Union(checkLocations));
                }
            }
        }
        return possibleLocations;
    }
コード例 #43
0
ファイル: NodeStates.cs プロジェクト: EmmittJ/PoESkillTree
 /// <summary>
 /// Creates a new instance. The parameters are copied.
 /// </summary>
 public NodeStates(IEnumerable<GraphNode> searchSpace, IEnumerable<GraphNode> fixedTargetNodes, IEnumerable<GraphNode> variableTargetNodes)
 {
     _searchSpace = new List<GraphNode>(searchSpace);
     _fixedTargetNodes = new HashSet<GraphNode>(fixedTargetNodes);
     _variableTargetNodes = new HashSet<GraphNode>(variableTargetNodes);
     _allTargetNodes = new HashSet<GraphNode>(_variableTargetNodes.Union(_fixedTargetNodes));
     ComputeFields();
 }
コード例 #44
0
        private static void ReportIssues(SymbolAnalysisContext context, HashSet<ISymbol> usedSymbols,
            HashSet<ISymbol> declaredPrivateSymbols, HashSet<ISymbol> emptyConstructors,
            BidirectionalDictionary<ISymbol, SyntaxNode> fieldLikeSymbols)
        {
            var unusedSymbols = declaredPrivateSymbols
                .Except(usedSymbols.Union(emptyConstructors))
                .ToList();

            var alreadyReportedFieldLikeSymbols = new HashSet<ISymbol>();

            var unusedSymbolSyntaxPairs = unusedSymbols
                .SelectMany(unusedSymbol => unusedSymbol.DeclaringSyntaxReferences
                    .Select(r =>
                        new
                        {
                            Syntax = r.GetSyntax(),
                            Symbol = unusedSymbol
                        }));

            foreach (var unused in unusedSymbolSyntaxPairs)
            {
                var location = unused.Syntax.GetLocation();

                var canBeFieldLike = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol;
                if (canBeFieldLike)
                {
                    if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol))
                    {
                        continue;
                    }

                    var variableDeclaration = GetVariableDeclaration(unused.Syntax);
                    if (variableDeclaration == null)
                    {
                        continue;
                    }

                    var declarations = variableDeclaration.Variables
                        .Select(v => fieldLikeSymbols.GetByB(v))
                        .ToList();

                    if (declarations.All(d => unusedSymbols.Contains(d)))
                    {
                        location = unused.Syntax.Parent.Parent.GetLocation();
                        alreadyReportedFieldLikeSymbols.UnionWith(declarations);
                    }
                }

                context.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, location), context.Compilation);
            }
        }
コード例 #45
0
        static void Main(string[] args)
        {
            var BigCities = new HashSet<string>
            {
                "New York",
                "Manchester",
                "Sheffield",
                "Paris"
            };

            string[] citiesInUK =
            {
                "Sheffield",
                "Ripon",
                "Truro",
                "Manchester"
            };

            //// Generic code to find intersecting values.
            //BigCities.IntersectWith(citiesInUK);

            //foreach (string city in BigCities)
            //{
            //    Console.WriteLine(city);
            //}

            // Linq method
            // The linq method does create a new array.
            var IntersectCities = BigCities.Intersect(citiesInUK);
            foreach (string city in IntersectCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Union takes elements that are in either set and puts every element out once.
            var UnionCities = BigCities.Union(citiesInUK);
            foreach (string city in UnionCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Every element that is in the first set, but not in the second set.
            var ExceptCities = BigCities.Except(citiesInUK);
            foreach (string city in ExceptCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Which elements appear in either one but not in both collections.
            BigCities.SymmetricExceptWith(citiesInUK);
            foreach (string city in BigCities)
            {
                Console.WriteLine(city);
            }
        }
コード例 #46
0
ファイル: DAG.cs プロジェクト: plasma-umass/DataDebug
 private bool traversalHasLoop(AST.Address current_addr, Dictionary<AST.Address, AST.Address> visited, AST.Address from_addr)
 {
     // base case 1: loop check
     if (visited.ContainsKey(current_addr))
     {
         return true;
     }
     // base case 2: an input cell
     if (!_formulas.ContainsKey(current_addr))
     {
         return false;
     }
     // recursive case (it's a formula)
     // check both single inputs and the inputs of any vector inputs
     bool OK = true;
     HashSet<AST.Address> single_inputs = _f2i[current_addr];
     HashSet<AST.Address> vector_inputs = new HashSet<AST.Address>(_f2v[current_addr].SelectMany(addrs => addrs.Addresses()));
     foreach (AST.Address input_addr in vector_inputs.Union(single_inputs))
     {
         if (OK)
         {
             // new dict to mark visit
             var visited2 = new Dictionary<AST.Address, AST.Address>(visited);
             // mark visit
             visited2.Add(current_addr, from_addr);
             // recurse
             OK = OK && !traversalHasLoop(input_addr, visited2, from_addr);
         }
     }
     return !OK;
 }
コード例 #47
0
        protected override void DoAction()
        {
            var phrases = GetEntitiesToProcess();
            foreach (var phrase in phrases) {
                var domains = SpywordsQueryWrapper.GetDomainsForPhrase(phrase.Text);
                phrase.Datecollected = DateTime.UtcNow;

                var statsContainer = _phraseStatsContainer.Match(domains).Value;
                var resultRows = _containerSplitToTr.Matches(statsContainer);
                if (resultRows.Count == 3) {
                    phrase.Status = PhraseStatus.Collected;
                    var yandexRowResult = _extractTdResult.Matches(resultRows[1].Value);
                    var googleRowResult = _extractTdResult.Matches(resultRows[2].Value);
                    phrase.Showsgoogle =
                        StringParser.ToInt(googleRowResult[1].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(int));
                    phrase.Showsyandex =
                        StringParser.ToInt(yandexRowResult[1].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(int));
                    phrase.Advertisersgoogle =
                        StringParser.ToShort(googleRowResult[2].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(short));
                    phrase.Advertisersyandex =
                        StringParser.ToShort(yandexRowResult[2].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(short));

                    var domainsForPhraseYandex = SpywordsQueryWrapper.GetDomainsForPhraseYandex(phrase.Text);

                    var yandexDomains = GetDomains(_yandexDomainBlockRegex.Match(domains).Value);
                    var advancedYandexDomains =
                        GetDomains(_allDomainsListYandexContainer.Match(domainsForPhraseYandex).Value);
                    yandexDomains = new HashSet<string>(yandexDomains.Union(advancedYandexDomains).Distinct());

                    var googleDomains = GetDomains(_googleDomainBlockRegex.Match(domains).Value);
                    try {
                        TaskRunner.Instance.AddAction(() => {
                            var domainEntities = new List<DomainEntity>(yandexDomains.Union(googleDomains).Distinct().Select(GetDomainEntity));
                            foreach(var domainEntity in domainEntities) {
                                var seType = (
                                    (yandexDomains.Contains(domainEntity.Domain)
                                        ? SearchEngine.Yandex
                                        : SearchEngine.Default) |
                                    (googleDomains.Contains(domainEntity.Domain)
                                        ? SearchEngine.Google
                                        : SearchEngine.Default));

                                CreateOrUpdateDomainPhrase(domainEntity, phrase, seType, SourceType.Context);
                            }
                        });
                    }
                    catch (Exception ex) {
                        phrase.Status = PhraseStatus.Error;
                        Logger.Error(string.Format("PhraseID={0}\r\n{1}", phrase.ID, ex));
                    }
                } else {
                    phrase.Status = PhraseStatus.Error;
                    Logger.Error("Нет трёх строк в таблице статистики запроса для {0} ID={1}", phrase.Text, phrase.ID);
                }

                phrase.Save();
            }
        }
コード例 #48
0
        public IEnumerable<Pair<PDLPred,double>> SynthesizeUnderapproximationPDL(HashSet<char> alphabet, Automaton<BDD> dfa, CharSetSolver solver, StringBuilder sb, long timeout)
        {
            #region TestSets for equiv
            var mytests = DFAUtilities.MyHillTestGeneration(alphabet, dfa, solver);
            var posMN = mytests.First;
            var negMN = mytests.Second;
            var tests = DFAUtilities.GetTestSets(dfa, alphabet, solver);
            var positive = tests.First;
            var negative = tests.Second;
            foreach (var t in posMN)
                positive.Remove(t);
            foreach (var t in negMN)
                negative.Remove(t);
            #endregion

            #region Accessory variables
            bool checkNeeded = false;
            string hash = "";
            HashSet<string> visited = new HashSet<string>();
            HashSet<string> newNodes = new HashSet<string>();
            List<Pair<PDLPred, double>> subsetPhis = new List<Pair<PDLPred, double>>();
            timer = new Stopwatch();
            timer.Start();
            #endregion

            InitializeSearchParameters(alphabet, dfa, solver);


            for (maxWidth = 3; true; maxWidth++)
            {
                int limit = (int)(Math.Sqrt(maxWidth));
                int limitH = (int)(Math.Sqrt(maxWidth + 5));
                maxStrLength = Math.Min(dfa.StateCount + 1, limit + 2);
                highestNum = Math.Min(limitH, dfa.StateCount - 1);
                substrTot = limit;
                connectivesTot = limit;
                setCountTot = limit;
                maxEmptyString = Math.Max(1, limit - 1);

                newNodes = new HashSet<string>();

                foreach (var phi in EnumeratePDLpred(new HashSet<string>(), new HashSet<string>()))
                {
                    #region run for at most timeout
                    if (timer.ElapsedMilliseconds > timeout)
                    {
                        subsetPhis.Sort(ComparePairsPhiDoubleByDouble);
                        timer.Stop();
                        return subsetPhis;
                    }
                    #endregion

                    #region Check decider to avoid repetition
                    hash = string.Format(
                        "{0},{1},{2},{3},{4},{5},{6}",
                        maxWidthC, maxStrLengthC, highestNumC, substrTotC, connectivesTotC, setCountTotC, maxEmptyStringC);
                    checkNeeded = !(visited.Contains(hash));
                    #endregion

                    if (checkNeeded)
                    {
                        newNodes.Add(hash);

                        #region add it to set of results if it is a subset
                        if (CorrectOnNegSet(phi, negMN) && CorrectOnNegSet(phi, negative))
                        {
                            var phiDfa = phi.GetDFA(alphabet, solver);
                            if (!phiDfa.IsEmpty)
                                if (phiDfa.Minus(dfa, solver).IsEmpty)
                                    subsetPhis.Add(
                                        new Pair<PDLPred, double>(
                                            phi,
                                            (double)phi.GetFormulaSize() / DFADensity.GetDFARatio(dfa, phiDfa, alphabet, solver, true)
                                        )
                                    );
                        }
                        #endregion
                    }
                }
                visited = new HashSet<string>(visited.Union(newNodes));
            }

        }
コード例 #49
0
    public void OnEnable()
    {
        editorSettings = JointEditorSettings.Singleton;

        if (editorSettings == null) {
            return;
        }

        var defaultNames = new HashSet<string> {"slider", "lock", "offset"};
        var childControlNames = GetControlNames();

        if (defaultNames.Overlaps(childControlNames)) {
            Debug.LogError("Reserved control names: " +
                           String.Join(",", defaultNames.Intersect(childControlNames)
                                                        .ToArray()) + ".");
        }
        controlNames = new HashSet<string>(defaultNames.Union(childControlNames));

        if (EditorHelpers.AllowMultiObjectAccess) {
            var allSettings =
                targets.Cast<Joint2D>()
                       .Select(joint2D => SettingsHelper.GetOrCreate(joint2D))
                       .Where(jointSettings => jointSettings != null)
                       .Cast<Object>()
                       .ToList();

            if (allSettings.Count > 0) {
                serializedSettings = new SerializedObject(allSettings.ToArray());
            } else {
                serializedSettings = null;
            }
        } else {
            if (target) {
                serializedSettings = new SerializedObject(new Object[] {SettingsHelper.GetOrCreate(target as Joint2D)});
            } else {
                serializedSettings = null;
            }
        }
    }
コード例 #50
0
ファイル: ExpressionEvaluator.cs プロジェクト: TerabyteX/main
        private static ISet<Namespace> EvaluateSet(ExpressionEvaluator ee, Node node)
        {
            var n = (SetExpression)node;
            ISet<Namespace> result;
            if (!ee.GlobalScope.NodeVariables.TryGetValue(node, out result)) {
                var values = new HashSet<Namespace>();
                foreach (var x in n.Items) {
                    values.Union(ee.Evaluate(x));
                }

                result = new DictionaryInfo(values, values, ee.ProjectState, ee.GlobalScope.ShowClr).SelfSet;
                ee.GlobalScope.NodeVariables[node] = result;
            }
            return result;
        }
コード例 #51
0
ファイル: Synchronizer.cs プロジェクト: mono0x/SecretSecret
        private void SynchronizeFiles(string leftRoot, string rightRoot)
        {
            var leftFiles =
                new HashSet<string>(Directory.GetFiles(leftRoot).Select(p => RelativePath(Left, p)));
            var rightFiles =
                new HashSet<string>(Directory.GetFiles(rightRoot).Select(p => RelativePath(Right, p)));
            var files = new HashSet<string>(leftFiles.Union(rightFiles));

            foreach (var file in files)
            {
                var left = Path.Combine(Left, file);
                var right = Path.Combine(Right, file);
                var leftExists = File.Exists(left);
                var rightExists = File.Exists(right);
                if (leftExists && rightExists)
                {
                    var diff = (File.GetLastWriteTime(left) - File.GetLastWriteTime(right)).Ticks;
                    if (diff > 0)
                    {
                        CopyWithEncrypt(left, right);
                    }
                    else if (diff < 0)
                    {
                        CopyWithDecrypt(right, left);
                    }
                }
                else if (leftExists && !rightExists)
                {
                    if (PreviousRightFiles.Contains(right))
                    {
                        File.Delete(left);
                    }
                    else
                    {
                        CopyWithEncrypt(left, right);
                    }
                }
                else if (!leftExists && rightExists)
                {
                    if (PreviousLeftFiles.Contains(left))
                    {
                        File.Delete(right);
                    }
                    else
                    {
                        CopyWithDecrypt(right, left);
                    }
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        }
コード例 #52
0
ファイル: Synchronizer.cs プロジェクト: mono0x/SecretSecret
        private void SynchronizeChildren(string leftRoot, string rightRoot)
        {
            var leftDirectories =
                new HashSet<string>(Directory.GetDirectories(leftRoot).Select(p => RelativePath(Left, p)));
            var rightDirectories =
                new HashSet<string>(Directory.GetDirectories(rightRoot).Select(p => RelativePath(Right, p)));
            var directories = new HashSet<string>(leftDirectories.Union(rightDirectories));

            foreach (var directory in directories)
            {
                var left = Path.Combine(Left, directory);
                var right = Path.Combine(Right, directory);
                var leftExists = Directory.Exists(left);
                var rightExists = Directory.Exists(right);
                if (leftExists && rightExists)
                {
                    SynchronizeDirectory(left, right);
                }
                else if (leftExists && !rightExists)
                {
                    if (PreviousRightDirectories.Contains(right))
                    {
                        Directory.Delete(left, true);
                    }
                    else
                    {
                        Directory.CreateDirectory(right);
                        SynchronizeDirectory(left, right);
                    }
                }
                else if (!leftExists && rightExists)
                {
                    if (PreviousLeftDirectories.Contains(left))
                    {
                        Directory.Delete(right, true);
                    }
                    else
                    {
                        Directory.CreateDirectory(left);
                        SynchronizeDirectory(left, right);
                    }
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        }
コード例 #53
0
ファイル: DAG.cs プロジェクト: plasma-umass/DataDebug
 // this is mostly for diagnostic purposes
 public int numberOfInputCells()
 {
     var v_cells = new HashSet<AST.Address>(_all_vectors.KeysT.SelectMany(rng => rng.Addresses()));
     var sc_cells = new HashSet<AST.Address>(_i2f.Values.SelectMany(addr => addr));
     var all = v_cells.Union(sc_cells);
     return all.Count();
 }
コード例 #54
0
ファイル: RespellerDlg.cs プロジェクト: bbriggs/FieldWorks
		void CheckForOtherOccurrences()
		{
			var allAnalysesCandidatesOfWordform = new List<IAnalysis>
													{
														m_srcwfiWordform
													};
			foreach (var anal in m_srcwfiWordform.AnalysesOC)
			{
				allAnalysesCandidatesOfWordform.Add(anal);
				foreach (var gloss in anal.MeaningsOC)
					allAnalysesCandidatesOfWordform.Add(gloss);
			}
			var allUsedSegments = new HashSet<ISegment>();
			foreach (var segment in m_cache.ServiceLocator.GetInstance<ISegmentRepository>().AllInstances().Where(
				segment => segment.AnalysesRS.Any(allAnalysesCandidatesOfWordform.Contains)))
			{
				allUsedSegments.Add(segment);
			}
			// There are 'other' occurrences if some of the real ones aren't in the displayed list.
			if (m_repoSeg == null)
				m_repoSeg = m_cache.ServiceLocator.GetInstance<ISegmentRepository>();
			var enabledSegments = new HashSet<ISegment>();
			foreach (int hvoFake in m_enabledItems)
			{
				int hvoSeg = m_specialSda.get_ObjectProp(hvoFake, ConcDecorator.kflidSegment);
				if (hvoSeg > 0)
					enabledSegments.Add(m_repoSeg.GetObject(hvoSeg));
			}
			m_fOtherOccurrencesExist = allUsedSegments.Union(enabledSegments).Count() != allUsedSegments.Count();
		}
コード例 #55
0
        /// <summary>
        /// Resolves the type of the controller.
        /// </summary>
        /// <param name="areaName">Name of the area.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <returns>Controller type</returns>
        public Type ResolveControllerType(string areaName, string controllerName)
        {
            // Is the type cached?
            string cacheKey = areaName + "_" + controllerName;
            if (Cache.ContainsKey(cacheKey))
            {
                return Cache[cacheKey];
            }

            // Find controller details
            IEnumerable<string> areaNamespaces = FindNamespacesForArea(areaName, this.routes);

            string area = areaName;
            string controller = controllerName;

            // Find controller type
            Type controllerType;
            HashSet<string> namespaces = null;
            if (areaNamespaces != null)
            {
                areaNamespaces = (from ns in areaNamespaces
                                  where ns != "Elmah.Mvc"
                                  where !this.areaNamespacesToIgnore.Contains(ns)
                                  select ns).ToList();
                if (areaNamespaces.Any())
                {
                    namespaces = new HashSet<string>(areaNamespaces, StringComparer.OrdinalIgnoreCase);
                    if (string.IsNullOrEmpty(areaName))
                    {
                        namespaces = new HashSet<string>(namespaces.Union(this.controllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
                    }
                }
            }
            else if (this.controllerBuilder.DefaultNamespaces.Count > 0)
            {
                namespaces = this.controllerBuilder.DefaultNamespaces;
            }
            controllerType = GetControllerTypeWithinNamespaces(area, controller, namespaces);

            // Cache the result
            Cache.Add(cacheKey, controllerType);

            // Return
            return controllerType;
        }
コード例 #56
0
ファイル: MainWindow.cs プロジェクト: fgeraci/CS195-Core
 /// <summary>
 /// Logic that handles selecting two groups of event stubs, and then executing a given action when
 /// both groups are selected and the Finish button is pressed.
 /// </summary>
 private void InitDualGroupSelection(Action<HashSet<EventStub>, HashSet<EventStub>> onSelectionEnd)
 {
     HashSet<EventStub> firstSet = new HashSet<EventStub>();
     HashSet<EventStub> secondSet = new HashSet<EventStub>();
     //all onClick actions
     Action<EventStub> highlightGreen = (EventStub evnt) => SetEventColor(evnt, Color.green);
     Action<EventStub> highlightMagenta = (EventStub evnt) => SetEventColor(evnt, Color.magenta);
     Action<EventStub> addToFirst = (EventStub e) => firstSet.Add(e);
     Action<EventStub> addToSecond = (EventStub e) => secondSet.Add(e);
     onEventLeftClick.Add(addToFirst);
     onEventLeftClick.Add(highlightGreen);
     ActionBar bar = new ActionBar(true);
     bar.AddButton("Cancel", () =>
     {
         onEventLeftClick.Remove(addToFirst);
         onEventLeftClick.Remove(addToSecond);
         onEventLeftClick.Remove(highlightGreen);
         onEventLeftClick.Remove(highlightMagenta);
         ResetEventColors(firstSet.Union(secondSet));
         parent.PopActionBar();
     });
     bar.AddButton("Next", () => 
         {
             onEventLeftClick.Remove(addToFirst);
             onEventLeftClick.Remove(highlightGreen);
             onEventLeftClick.Add(highlightMagenta);
             onEventLeftClick.Add(addToSecond);
             bar.RemoveButton("Next");
             bar.AddButton("Finish", () =>
             {
                 onEventLeftClick.Remove(addToSecond);
                 parent.PopActionBar();
                 onEventLeftClick.Remove(highlightMagenta);
                 ResetEventColors(firstSet.Union(secondSet));
                 onSelectionEnd.Invoke(firstSet, secondSet);
             });
         });
     parent.AddActionBar(bar);
 }
コード例 #57
0
 private static bool IndirectlyDependsOnItself(Node target,Node current,ref HashSet<Node> traveledPath)
 {
     foreach (var dependency in current.SiblingDependencies)
     {
         if(traveledPath.Contains(dependency))
             continue;
         if (dependency == target)
             return true;
         var newPath = traveledPath.Union(new[]{dependency}).ToHashSet();
         if (IndirectlyDependsOnItself(target, dependency, ref newPath))
         {
             traveledPath = newPath;
             return true;
         }
     }
     return false;
 }
コード例 #58
0
        static void Main(string[] args)
        {
            List<int> arr1 = new List<int>();
            List<int> arr3 = new List<int>();
            List<int> arr2 = new List<int>();
            int i = 0;
            arr1.Add(1);
            arr2.Add(2);
            arr3.Add(2);
            do
            {
                i++;
                arr1.Add(2 * arr1[i - 1] + 3);
                arr2.Add(3 * arr2[i - 1] + 1);
                arr3.Add(2 * arr3[i - 1] - 1);
            } while (arr3[i] < 100000);
            arr1.RemoveAll(item => item > 100000);
            arr2.RemoveAll(item => item > 100000);
            arr3.RemoveAt(i);

            HashSet<int> hesh1 = new HashSet<int>(arr1);
            HashSet<int> hesh2 = new HashSet<int>(arr2);
            HashSet<int> hesh3 = new HashSet<int>(arr3);

            int[] intersect1 = hesh1.Intersect(hesh2).ToArray();
            Console.WriteLine("arr1*arr2");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh1.Intersect(hesh3).ToArray();
            Console.WriteLine("arr1*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh2.Intersect(hesh3).ToArray();
            Console.WriteLine("arr2*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh1.Intersect(hesh2).Intersect(hesh3).ToArray();
            Console.WriteLine("arr1*arr2*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            int[] union1 = hesh1.Union(hesh2).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr2");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh1.Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh2.Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr2+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh1.Union(hesh2).Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr2+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
        }
        public void HashSetShouldUnionElementCorrectly()
        {
            var set1 = new HashSet<int>();
            var set2 = new HashSet<int>();
            set1.Add(1);
            set1.Add(2);

            set2.Add(2);
            set2.Add(3);
            set2.Add(4);

            var union = set1.Union(set2);

            Assert.IsTrue(union.Find(1));
            Assert.IsTrue(union.Find(2));
            Assert.IsTrue(union.Find(3));
            Assert.IsTrue(union.Find(4));
            Assert.AreEqual(4, union.Count);
        }
コード例 #60
-1
        private IEnumerable<string> GetTransitiveClosure(string state)
        {
            var result = new HashSet<string> { state };
            while (result.Union(result.SelectMany(s => GetTransitions(s, null))).Distinct().Count() != result.Count)
            {
                result.SelectMany(s => GetTransitions(s, null)).ToArray().ForEach(s => result.Add(s));
            }

            return result;
        }