private static IEnumerable<Type> getTypes(Type sourceType)
        {
            Queue<Type> pending = new Queue<Type>();
            HashSet<Type> visited = new HashSet<Type>();
            pending.Enqueue(sourceType);

            while (pending.Count != 0)
            {
                Type type = pending.Dequeue();
                visited.Add(type);
                yield return type;

                if (type.BaseType != null)
                {
                    if (!visited.Contains(type.BaseType))
                    {
                        pending.Enqueue(type.BaseType);
                    }
                }

                foreach (Type interfaceType in type.GetInterfaces())
                {
                    if (!visited.Contains(interfaceType))
                    {
                        pending.Enqueue(interfaceType);
                    }
                }
            }
        }
Example #2
0
 static void Main(string[] args)
 {
     var letters = new HashSet<char>("the quick brown fox");
     Console.WriteLine(letters.Contains('t')); // true
     Console.WriteLine(letters.Contains('j')); // false
     foreach (char c in letters)
     {
         Console.Write(c); // the quickbrownfx
     }
     letters.IntersectWith("aeiou");
     foreach (char c in letters)
     {
         Console.Write(c); // euio
     }
     var letters2 = new HashSet<char>("the quick brown fox");
     letters2.ExceptWith("aeiou");
     foreach (char c in letters2)
     {
         Console.Write(c); // th qckbrwnfx
     }
     var letters3 = new HashSet<char>("the quick brown fox");
     letters3.SymmetricExceptWith("the lazy brown fox");
     foreach (char c in letters3)
     {
         Console.Write(c); // quicklazy
     }
 }
        public Task<PermissionSet> GetPermissions(IReadOnlyList<SignatureEvidence> authentication, LedgerPath path, bool recursiveOnly, string recordName)
        {
            HashSet<string> identities = new HashSet<string>(authentication.Select(evidence => keyEncoder.GetPubKeyHash(evidence.PublicKey)), StringComparer.Ordinal);
            LedgerPath pathRecordName;

            // If the path is root and the record name is a tird-party asset owned by the current identity,
            // arbitrary modification of the balance is allowed
            if (LedgerPath.TryParse(recordName, out pathRecordName)
                && thirdPartyAssetPath.IsStrictParentOf(pathRecordName)
                && path.Segments.Count == 0
                && identities.Contains(pathRecordName.Segments[thirdPartyAssetPath.Segments.Count]))
            {
                return Task.FromResult(new PermissionSet(accountNegative: Access.Permit));
            }

            // Account /asset/p2pkh/[addr]/
            if (thirdPartyAssetPath.IsStrictParentOf(path)
                && path.Segments.Count == thirdPartyAssetPath.Segments.Count + 1
                && keyEncoder.IsP2pkh(path.Segments[path.Segments.Count - 1]))
            {
                Access ownAccount = identities.Contains(path.Segments[path.Segments.Count - 1]) && recordName != DynamicPermissionLayout.AclResourceName
                    ? Access.Permit : Access.Unset;

                return Task.FromResult(new PermissionSet(
                    accountModify: Access.Permit,
                    accountCreate: Access.Permit,
                    accountSpend: ownAccount,
                    dataModify: ownAccount));
            }
            else
            {
                return Task.FromResult(new PermissionSet());
            }
        }
        /// <summary>
        /// Writes index files into the specified directory.
        /// </summary>
        /// <param name="indexDirectory">The directory into which the index files should be written.</param>
        /// <param name="recordMapper">The mapper for the records.</param>
        /// <param param name="records">The records which should be written.</param>
        public void WriteDirectory(DirectoryInfo indexDirectory, IRecordMapper<string> recordMapper, IEnumerable<IReferenceRecord> records)
        {
            if (!indexDirectory.Exists)
            {
                indexDirectory.Create();
            }

            var directoryNames = new HashSet<string>();
            foreach (var directory in indexDirectory.GetDirectories())
            {
                if (!directoryNames.Contains(directory.Name))
                {
                    directoryNames.Add(directory.Name);
                }
            }
            foreach (var record in records)
            {
                var directoryName = recordMapper.Map(record);
                if (!directoryNames.Contains(directoryName))
                {
                    indexDirectory.CreateSubdirectory(directoryName);
                    directoryNames.Add(directoryName);
                }

                // Write index files into the index directory
            }
        }
Example #5
0
    long Solve(int N, List<int> A, int I, HashSet<int> used, int need)
    {
        long result = 0;
          for (int i = 1; i <= N; i++) {

         if (used.Contains(i)) {
            continue;
         }

         var n = i - A[I] > 0 ? need - (i - A[I]) : need;
         if (n <= 0) {
            int c = 0;
            for (int j = 1; j <= N; j++) {
               if (!used.Contains(j) && j != i) {
                  c++;
               }
            }
            result += Prod(Enumerable.Range(1, c).ToList());
         } else {
            used.Add(i);
            result += Solve(N, A, I + 1, used, n);
            used.Remove(i);
         }
          }

          return result;
    }
Example #6
0
 public List<Graph> ConnectedComponents()
 {
     List<Graph> ret = new List<Graph>();
     HashSet<int> visited = new HashSet<int>();
     Queue<int> queue = new Queue<int>();
     ForEachVertex((v) =>
         {
             if (!visited.Contains(v))
             {
                 Graph g = new Graph();
                 queue.Enqueue(v);
                 visited.Add(v);
                 while (queue.Count != 0)
                 {
                     int u = queue.Dequeue();
                     g.storage[u] = storage[u];
                     ForEachNeighbor(u, (w) =>
                         {
                             if (!visited.Contains(w))
                             {
                                 queue.Enqueue(w);
                                 visited.Add(w);
                             }
                         });
                 }
                 ret.Add(g);
             }
         });
     return ret;
 }
        internal IEnumerable<SortingInfo> GetFullSort() {
            var memo = new HashSet<string>();
            var result = new List<SortingInfo>();

            if(HasGroups) {
                foreach(var g in Group) {
                    if(memo.Contains(g.Selector))
                        continue;

                    memo.Add(g.Selector);
                    result.Add(g);
                }
            }

            if(HasSort) {
                foreach(var s in Sort) {
                    if(memo.Contains(s.Selector))
                        continue;

                    memo.Add(s.Selector);
                    result.Add(s);
                }
            }

            IEnumerable<string> requiredSort = new string[0];

            if(HasDefaultSort)
                requiredSort = requiredSort.Concat(new[] { DefaultSort });

            if(HasPrimaryKey)
                requiredSort = requiredSort.Concat(PrimaryKey);

            return Utils.AddRequiredSort(result, requiredSort);
        }
        public int CalculateBudgetUsed()
        {
            this.edges.Sort();
            var graph = BuildGraph();
            var spanningTreeNodes = new HashSet<int>();
            var connectedEdges = this.edges
                .Where(e => e.IsConnected);
            foreach (var connectedEdge in connectedEdges)
            {
                spanningTreeNodes.Add(connectedEdge.StartNode);
                spanningTreeNodes.Add(connectedEdge.EndNode);
            }

            foreach (var edge in edges)
            {
                if (!spanningTreeNodes.Contains(edge.StartNode))
                {
                    Prim(graph, spanningTreeNodes, edge.StartNode);
                }

                if (!spanningTreeNodes.Contains(edge.EndNode))
                {
                    Prim(graph, spanningTreeNodes, edge.EndNode);
                }
            }

            var budgetUsed = this.startBudget - this.leftBudget;
            return budgetUsed;
        }
        internal override ThreeValuedLogic Evaluate(Strategy strategy)
        {
            var containing = new HashSet<IObject>(this.containingEnumerable);

            if (this.associationType.IsMany)
            {
                var associations = strategy.GetCompositeAssociations(this.associationType);
                foreach (var assoc in associations)
                {
                    if (containing.Contains((IObject)assoc))
                    {
                        return ThreeValuedLogic.True;
                    }
                }

                return ThreeValuedLogic.False;
            }

            var association = strategy.GetCompositeAssociation(this.associationType);
            if (association != null)
            {
                return containing.Contains(association)
                           ? ThreeValuedLogic.True
                           : ThreeValuedLogic.False;
            }

            return ThreeValuedLogic.False;
        }
        public void SimpleMergeSucceeds()
        {
            var lengths = new[] { 1, 3, 4, 6 };
            var words = new[] { "car", "dog", "free", "sixpack" };

            var uniqueLengths = new HashSet<int>();
            var uniqueWords = new HashSet<string>();
            var pairs = new HashSet<Tuple<int, string>>();

            lengths.Merge(
                words,
                l => l,
                w => w.Length,
                l => uniqueLengths.Add(l),
                w => uniqueWords.Add(w),
                (l, w) => pairs.Add(Tuple.Create(l, w))
            );

            Assert.AreEqual(2, uniqueLengths.Count);
            Assert.IsTrue(uniqueLengths.Contains(1));
            Assert.IsTrue(uniqueLengths.Contains(6));

            Assert.AreEqual(1, uniqueWords.Count);
            Assert.IsTrue(uniqueWords.Contains("sixpack"));

            Assert.AreEqual(3, pairs.Count);
            Assert.IsTrue(pairs.Contains(Tuple.Create(3, "car")));
            Assert.IsTrue(pairs.Contains(Tuple.Create(3, "dog")));
            Assert.IsTrue(pairs.Contains(Tuple.Create(4, "free")));
        }
        public void MergeWithNullKeysSucceeds()
        {
            var wordsA = new[] { "car", "dog", "free", null };
            var wordsB = new[] { "car", "dog", "free", "sixpack" };

            var uniqueA = new HashSet<string>();
            var uniqueB = new HashSet<string>();
            var pairs = new HashSet<string>();

            wordsA.Merge(
                wordsB,
                a => a,
                b => b,
                a => uniqueA.Add(a),
                b => uniqueB.Add(b),
                (a, b) => pairs.Add(a)
            );

            Assert.AreEqual(1, uniqueA.Count);
            Assert.IsTrue(uniqueA.Contains(null));

            Assert.AreEqual(1, uniqueB.Count);
            Assert.IsTrue(uniqueB.Contains("sixpack"));

            Assert.AreEqual(3, pairs.Count);
            Assert.IsTrue(pairs.Contains("car"));
            Assert.IsTrue(pairs.Contains("dog"));
            Assert.IsTrue(pairs.Contains("free"));
        }
        public int LongestConsecutiveSolution(int[] nums)
        {
            int length = nums.Length;
            HashSet<int> set = new HashSet<int>();
            int max=0;
            foreach(int cur in nums)
                set.Add(cur);

            foreach (int cur in nums)
            {
                int len=1;
                int left = cur - 1;
                int right = cur + 1;
                while (set.Contains(left))
                {
                    len++;
                    set.Remove(left);
                    left--;
                }
                while (set.Contains(right))
                {
                    len++;
                    set.Remove(left);
                    right++;
                }

                max = max > len ? max : len;
            }
            return max;
        }
Example #13
0
        static void Main(string[] args)
        {
            int number = int.Parse(Console.ReadLine());

            HashSet<int> NoPrime = new HashSet<int>();

            for (int x = 2; x < number; x++)
            {
                for (int y = x * 2; y < number; y = y + x)
                {
                    if (!NoPrime.Contains(y))
                    {
                        NoPrime.Add(y);
                    }
                }
            }

            Console.Write("2");

            for (int z = 3; z <= number ; z++)
            {
                if (z != number)
                {
                    if (!NoPrime.Contains(z))
                    {
                        Console.Write(", " + z);
                    }
                }
            }
            Console.WriteLine();
        }
Example #14
0
        public override string Solve()
        {
            var denominators = new List<BigInteger>();
            var numbersToSkip = new HashSet<decimal> { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
            for (decimal numerator = 10; numerator < 100; numerator++) {
                for (decimal denominator = 10; denominator < 100; denominator++) {
                    if (numbersToSkip.Contains(numerator) && numbersToSkip.Contains(denominator)) {
                        continue;
                    }
                    if (numerator == denominator) {
                        continue;
                    }

                    decimal? numberInBoth = GetNumberInboth(numerator, denominator);
                    if (numberInBoth != null) {
                        var one = numerator / denominator;
                        if (one > 1) continue;

                        var newDenominator = RemoveNumber(numberInBoth.Value, denominator);

                        if (newDenominator == 0) {
                            continue;
                        }
                        var newNumerator = RemoveNumber(numberInBoth.Value, numerator);
                        var two = newNumerator / newDenominator;
                        if (one == two) {
                            denominators.Add(BigInteger.Parse(newDenominator.ToString()));
                        }
                    }
                }
            }

            var product = denominators[0] * denominators[1] * denominators[2];
            return product.ToString();
        }
    public void Reset(IEnumerable<ItemReference> refsToKeep)
    {
      if (refsToKeep.Any())
      {
        var refsToKeepHash = new HashSet<ItemReference>(refsToKeep);

        // Clean up the definitions as necessary
        var defnsToRemove = (from p in _allDefinitions where !refsToKeepHash.Contains(p.Value) select p.Key).ToList();
        foreach (var defnToRemove in defnsToRemove)
        {
          _allDefinitions.Remove(defnToRemove);
        }

        // Clean up the dependencies as necessary
        foreach (var depend in _allDependencies)
        {
          depend.Value.RemoveAllButMasterList(refsToKeepHash);
        }

        // Remove dependency information
        var itemsToRemove = (from p in _allItemDependencies where !refsToKeepHash.Contains(p.Key) select p.Key).ToList();
        foreach (var itemToRemove in itemsToRemove)
        {
          _allItemDependencies.Remove(itemToRemove);
        }
      }
      else
      {
        this.Reset();
      }
    }
Example #16
0
        public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) {
            if (user == null)
                return WindowsIdentity.GetAnonymous();
            
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, user.EmailAddress),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray()))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(user.Roles.ToArray());
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
        private List<KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>> FindReoccuringOperations(
            IEnumerable<BinaryExpressionSyntax> operations, SemanticModel semanticModel)
        {

            var originalList = operations.ToList();
            var copiedList = originalList.ToList();
            var duplicates = new List<KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>>();
            var alreadyFound = new HashSet<BinaryExpressionSyntax>();

            foreach (var oItem in originalList)
            {
                foreach (var cItem in copiedList)
                {
                    if (alreadyFound.Contains(oItem) && alreadyFound.Contains(cItem)) continue;

                    if (IsEqualButNotTheSame(oItem, cItem, semanticModel))
                    {
                        alreadyFound.Add(oItem);
                        alreadyFound.Add(cItem);
                        duplicates.Add(new KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>(oItem, cItem));
                        break;
                    }
                }
            }
            return duplicates;
        }
Example #18
0
        private TestType GetTestType(MethodInfo testMethod)
        {
            var uniqueAttributeTypes = new HashSet<string>();
            var allAttributes = testMethod.GetCustomAttributes();
            foreach (var attr in allAttributes)
            {
                uniqueAttributeTypes.Add(attr.GetType().Name);
            }

            if (uniqueAttributeTypes.Contains(typeof (TestCaseAttribute).Name))
            {
                if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name))
                {
                    return TestType.TestCasesShouldThrow;
                }
                
                return TestType.TestCasesNormal;
            }

            if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name))
            {
                return TestType.ShouldThrow;
            }

            return TestType.Normal;
        }
Example #19
0
 public static LinearLinkage Apply(IRandom random, LinearLinkage p1, LinearLinkage p2) {
   var length = p1.Length;
   var child = new LinearLinkage(length);
   var endNodes = new HashSet<int>();
   for (var i = 0; i < length; i++) {
     if ((p1[i] == i && p2[i] == i)
       || ((p1[i] == i || p2[i] == i) && random.NextDouble() < 0.5)) {
       child[i] = i;
       endNodes.Add(i);
     }
   }
   for (var i = 0; i < length; i++) {
     if (endNodes.Contains(i)) continue;
     var p1End = endNodes.Contains(p1[i]);
     var p2End = endNodes.Contains(p2[i]);
     if ((p1End && p2End) || (!p1End && !p2End)) {
       child[i] = random.NextDouble() < 0.5 ? p1[i] : p2[i];
     } else if (p1End) {
       child[i] = p1[i];
     } else {
       child[i] = p2[i];
     }
   }
   child.LinearizeTreeStructures();
   return child;
 }
 public void Create()
 {
     var collection = new HashSet<string> { "A", "B", "A" }.AsReadOnly();
     Assert.AreEqual(2, collection.Count);
     Assert.IsTrue(collection.Contains("A"));
     Assert.IsTrue(collection.Contains("B"));
 }
        protected IEnumerable<Bundle> CreateExternalBundlesFromReferences(IEnumerable<Bundle> bundlesArray, CassetteSettings settings)
        {
            var referencesAlreadyCreated = new HashSet<string>();
            foreach (var bundle in bundlesArray)
            {
                foreach (var reference in bundle.References)
                {
                    if (reference.IsUrl() == false) continue;
                    if (referencesAlreadyCreated.Contains(reference)) continue;

                    var externalBundle = CreateExternalBundle(reference, bundle, settings);
                    referencesAlreadyCreated.Add(externalBundle.Path);
                    yield return externalBundle;
                }
                foreach (var asset in bundle.Assets)
                {
                    foreach (var assetReference in asset.References)
                    {
                        if (assetReference.Type != AssetReferenceType.Url ||
                            referencesAlreadyCreated.Contains(assetReference.Path)) continue;

                        var externalBundle = CreateExternalBundle(assetReference.Path, bundle, settings);
                        referencesAlreadyCreated.Add(externalBundle.Path);
                        yield return externalBundle;
                    }
                }
            }
        }
        protected override void RunFilterImpl()
        {
            IEnumerable<Entity> relatedObjects = entity.EntitySet.GetRelatedEntities(entity, DegreeOfRelationshipsToShow);

            var hashSet = new HashSet<IEntity>(relatedObjects.Cast<IEntity>());
            schemaController.SetEntitiesAndRelationshipsToVisible(hashSet);

            // Add Parents
            foreach(var ent in relatedObjects)
            {
                if (ent.Parent == null) continue;
                if(hashSet.Contains(ent) && hashSet.Contains(ent.Parent))
                {
                    schemaController.SetVisibilityOfVirtualRelationship(ent.Parent, ent, Visibility.Visible);
                }
            }

            if (!ShowTables) return;

            // Get the mapped tables for the primary entity we are showing.
            var mappings = mappingSet.GetMappingsContaining(entity);

            HashSet<IEntity> tables = new HashSet<IEntity>(mappings.Select(m => m.FromTable).Cast<IEntity>());
            schemaController.SetEntitiesAndRelationshipsToVisible(tables);

            foreach(var m in mappings)
            {
                schemaController.SetVisibility(m, Visibility.Visible);
            }
        }
Example #23
0
        /// <summary>
        /// Determines which methods can be proxied from 
        /// the given <paramref name="baseType"/> and <paramref name="baseInterfaces"/>. 
        /// </summary>
        /// <remarks>By default, only public virtual methods will be proxied.</remarks>
        /// <param name="baseType">The base class of the proxy type currently being generated.</param>
        /// <param name="baseInterfaces">The list of interfaces that the proxy must implement.</param>
        /// <returns>A list of <see cref="MethodInfo"/> objects that can be proxied.</returns>
        public IEnumerable<MethodInfo> ChooseProxyMethodsFrom(Type baseType, IEnumerable<Type> baseInterfaces)
        {
            var results = new HashSet<MethodInfo>();

            var baseMethods = from method in baseType.GetMethods()
                              where method.IsVirtual && !method.IsFinal && !method.IsPrivate
                              select method;

            // Add the virtual methods defined
            // in the base type
            foreach (var method in baseMethods)
            {
                if (!results.Contains(method))
                    results.Add(method);
            }

            var interfaceMethods = from currentInterface in baseInterfaces
                                   from method in currentInterface.GetMethods()
                                   where method.IsPublic && method.IsVirtual &&
                                         !method.IsFinal && !results.Contains(method)
                                   select method;

            // Add the virtual methods defined
            // in the interface types
            foreach (var method in interfaceMethods)
            {
                results.Add(method);
            }

            return results;
        }
Example #24
0
        public HashSet<string> FindSynonymAttribute(string attribute, string category)
        {
            HashSet<string> answer = new HashSet<string>();
            answer.Add(attribute);
            if (categoryToAttributeset.ContainsKey(category) == false)
                return answer;

            if (attribute == "postal code" && category == "address")
            {
                attribute = "postal code";
            }

            List<string> synonymList = GetSynonymsByInstance(attribute);
            foreach (string synonym in synonymList)
                if (categoryToAttributeset[category].Contains(synonym)&&synonym.Length>=3)
                {
                    if (answer.Contains(synonym) == false) answer.Add(synonym);
                }

            string[] tokens = attribute.Split(' ');
            if (tokens.Count() != 1)
            {
                HashSet<string> subAnswer = FindSynonymAttribute(tokens[tokens.Count() - 1], category);
                foreach (string item in subAnswer)
                    if (answer.Contains(item) == false)
                    {
                        answer.Add(item);
                    }
            }
            return answer;
        }
Example #25
0
        private static MvcHtmlString[] RadioButtonListInternal(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, IDictionary<string, object> htmlAttributes) {
            if (String.IsNullOrEmpty(name)) {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
            }
            if (selectList == null) {
                throw new ArgumentNullException("selectList");
            }

            // If we haven't already used ViewData to get the entire list of items then we need to
            // use the ViewData-supplied value before using the parameter-supplied value.
            if (!usedViewData) {
                object defaultValue = htmlHelper.ViewData.Eval(name);

                if (defaultValue != null) {
                    IEnumerable defaultValues = new[] { defaultValue };
                    IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
                    HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
                    List<SelectListItem> newSelectList = new List<SelectListItem>();

                    foreach (SelectListItem item in selectList) {
                        item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
                        newSelectList.Add(item);
                    }

                    selectList = newSelectList;
                }
            }

            IEnumerable<MvcHtmlString> radioButtons = selectList.Select<SelectListItem, MvcHtmlString>(item => htmlHelper.RadioButton(name, item.Value, item.Selected, htmlAttributes));

            return radioButtons.ToArray();
        }
        public virtual void move(double deltaT, HashSet<Keys> keyPressed)
        {
            base.move();

            if (keyPressed.Contains(Keys.Left))
            {
                this.positionX += (deltaT) * playerSpeed;
            }

            if (keyPressed.Contains(Keys.Right))
            {
                this.positionX -= (deltaT) * playerSpeed;
            }

            this.munitionStock.move(deltaT, keyPressed, this);

            foreach(Missile m in Missile.misileList)
                if (!BasicShip.colitionTest(this,m))
                {
                    int old = this.live;
                    this.live -= m.live;
                    m.live -= old;

                }
        }
Example #27
0
        public bool run()
        {
            var triangleNumbers = new HashSet<long>();
            var pentagonalNumbers = new HashSet<long>();
            var hexagonalNumbers = new HashSet<long>();
            for (var n = 1L; ; n++)
            {
                long v1 = n * (n + 1) / 2;
                long v2 = n * (3 * n - 1) / 2;
                long v3 = n * (2 * n - 1);
                triangleNumbers.Add(v1);
                pentagonalNumbers.Add(v2);
                hexagonalNumbers.Add(v3);

                if ((pentagonalNumbers.Contains(v1) && hexagonalNumbers.Contains(v1)) ||
                    (triangleNumbers.Contains(v2) && hexagonalNumbers.Contains(v2)) ||
                    (triangleNumbers.Contains(v3) && pentagonalNumbers.Contains(v3)))
                {
                    {
                        if (triangleNumbers.Intersect(pentagonalNumbers)
                                .Intersect(hexagonalNumbers).Count() == 3)
                        {
                            break;
                        }
                    }
                }
            }

            var result =
                triangleNumbers.Intersect(pentagonalNumbers)
                    .Intersect(hexagonalNumbers).OrderBy(v => v).Last();

            return result == 1533776805;
        }
                /// <summary>
                /// Returns the lightest set of edges that would divide the graph in two components should they be removed.
                /// </summary>
                /// <param name="graph">The flow graph to calculate the minimum cut of.</param>
                /// <param name="source">The source of the flow.</param>
                /// <param name="sink">The sink of the flow.</param>
                /// <returns>A list containing the edges that make up the minimum cut.</returns>
                public static List<IFlowGraphEdge> MinCut(IGraph<IFlowGraphEdge> graph, uint source, uint sink)
                {
                    Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = BuildFlowGraph(graph);
                    MaxFlow(flowGraph, source, sink);

                    List<IFlowGraphEdge> cut = new List<IFlowGraphEdge>();
                    HashSet<uint> reachable = new HashSet<uint>();
                    Queue<uint> open = new Queue<uint>();

                    open.Enqueue(source);
                    reachable.Add(source);
                    while (open.Count > 0)
                    {
                        uint i = open.Dequeue();
                        foreach (uint j in flowGraph[i].Keys)
                            if (!reachable.Contains(j) && flowGraph[i][j].Residual > 0)
                            {
                                open.Enqueue(j);
                                reachable.Add(j);
                            }
                    }

                    foreach (uint i in reachable)
                    {
                        foreach (uint j in flowGraph[i].Keys)
                            if (!reachable.Contains(j))
                                cut.Add(flowGraph[i][j].Original);
                    }

                    return cut;
                }
Example #29
0
        static void Main(string[] args)
        {
            int n = ushort.Parse(Console.ReadLine());

            HashSet<int> noPrime = new HashSet<int> { };

            for (int x = 2; x < n; x++)
            {
                for (int y = x * 2; y < n; y = y + x)
                {
                    if (!noPrime.Contains(y))
                    {
                        noPrime.Add(y);
                    }
                }
            }
            Console.Write("2");

            for (int z = 3; z <= n; z++)
            {
                if (z != n)
                {
                    if (!noPrime.Contains(z))
                    {
                        Console.Write(", " + z);
                    }
                }

            }
            Console.WriteLine();
        }
Example #30
0
        /// <summary>
        /// This method removes duplicates from tile connections. This includes connections
        /// which are a subset of another connection.
        /// </summary>
        /// <param name="tileConnections"></param>
        /// <returns></returns>
        public static List<TileConnection> CleanDuplicatesFromTileCollectionList(List<TileConnection> tileConnections)
        {
            var dupes = new HashSet<TileConnection>();

            //compare every tile connection against every other to find the duplicates. This is slow.
            for (var tci = 0; tci < tileConnections.Count; tci++) {
                var tc = tileConnections[tci];
                for (var tci2 = tci + 1; tci2 < tileConnections.Count; tci2++) {
                    var tc2 = tileConnections[tci2];
                    if (!dupes.Contains(tc2) && tc2.IsDuplicateOrSubsetOf(tc)) {
                        dupes.Add(tc2);

                    } else if (!dupes.Contains(tc) && tc.IsDuplicateOrSubsetOf(tc2)) {
                        //By using else if we ensure that we don't add both tileconnections
                        //if they are exact duplicates
                        dupes.Add(tc);
                    }
                }
            }

            //remove all the duplicates
            dupes.ToList().ForEach( dup => {
                tileConnections.Remove(dup);
            });

            return tileConnections;
        }