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;
        }
        static void drawCodeGenerators(CodeGeneratorConfig codeGeneratorConfig, Type[] codeGenerators)
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Code Generators", EditorStyles.boldLabel);

            var enabledCodeGenerators = new HashSet<string>(codeGeneratorConfig.enabledCodeGenerators);

            var availableGeneratorNames = new HashSet<string>();
            foreach (var codeGenerator in codeGenerators) {
                availableGeneratorNames.Add(codeGenerator.Name);
                var isEnabled = enabledCodeGenerators.Contains(codeGenerator.Name);
                isEnabled = EditorGUILayout.Toggle(codeGenerator.Name, isEnabled);
                if (isEnabled) {
                    enabledCodeGenerators.Add(codeGenerator.Name);
                } else {
                    enabledCodeGenerators.Remove(codeGenerator.Name);
                }
            }

            foreach (var generatorName in codeGeneratorConfig.enabledCodeGenerators.ToArray()) {
                if (!availableGeneratorNames.Contains(generatorName)) {
                    enabledCodeGenerators.Remove(generatorName);
                }
            }

            var sortedCodeGenerators = enabledCodeGenerators.ToArray();
            Array.Sort(sortedCodeGenerators);
            codeGeneratorConfig.enabledCodeGenerators = sortedCodeGenerators;
        }
        /// <summary>
        /// Find Longest Consequitive Sequence
        /// </summary>
        /// <param name="arr">Source Array</param>
        /// <returns>Length of longest consecutive numbers</returns>
        public static int LongestConsecutiveSequenceLength(int[] arr)
        {
            HashSet<int> allElements = new HashSet<int>(arr);
            int maxConsecutiveLength = 1;
            while (allElements.Count > 0)
            {
                int firstValue = allElements.First();
                int leftElement = firstValue;
                int currentLength = 1;
                while (allElements.Contains(leftElement - 1))
                {
                    allElements.Remove(leftElement - 1);
                    leftElement--;
                    currentLength++;
                }

                int rightElement = firstValue;
                while (allElements.Contains(rightElement + 1))
                {
                    allElements.Remove(rightElement + 1);
                    rightElement++;
                    currentLength++;
                }

                if (currentLength > maxConsecutiveLength)
                {
                    maxConsecutiveLength = currentLength;
                }

                allElements.Remove(firstValue);
            }

            return maxConsecutiveLength;
        }
 public int LongestConsecutive(int[] num)
 {
     HashSet<int> hset = new HashSet<int>(num);
     int answer = 1;
     for (int i = 0; i < num.Length; i++)
     {
         int current = num[i];
         if (hset.Remove(current))
         {
             int tmp = 1;
             int higher = current +1;
             while (hset.Remove(higher++))
             {
                 tmp++;
             }
             int lower = current - 1;
             while (hset.Remove(lower--))
             {
                 tmp++;
             }
             answer = Math.Max(answer, tmp);
         }
     }
     return answer;
 }
Example #5
0
        public void AddRemove()
        {
            var set = new HashSet<int>();
              foreach (int item in Enumerable.Range(100, 100))
              {
            bool added = set.Add(item);
            Assert.IsTrue(added);
              }

              Assert.AreEqual(100, set.Count);
              Assert.IsFalse(set.Add(120));

              foreach (int item in Enumerable.Range(120, 20))
              {
            bool removed = set.Remove(item);
            Assert.IsTrue(removed);
              }

              Assert.AreEqual(80, set.Count);
              Assert.IsFalse(set.Remove(120));

              foreach (int item in Enumerable.Range(100, 200))
            set.Add(item);

              Assert.AreEqual(200, set.Count);
        }
        public int LongestConsecutive(int[] num)
        {
            int max = 0;
            HashSet<int> hashSet = new HashSet<int>(num);

            foreach (int val in num)
            {
                if (hashSet.Remove(val))
                {
                    int tempResult = 1;
                    int upperVal = val + 1;
                    while (hashSet.Remove(upperVal++))
                    {
                        tempResult++;
                    }
                    int lowerVal = val - 1;
                    while (hashSet.Remove(lowerVal--))
                    {
                        tempResult++;
                    }
                    max = Math.Max(max, tempResult);
                }
            }

            return max;
        }
    public int[] FindBest()
    {
      var remaining = new HashSet<Point>(_cities);
      var first = remaining.First();
      var route = new List<Point> { first };
      remaining.Remove(first);

      var numericRoute = new List<int>{_cities.IndexOf(first)};
      var distance = 0.0d;
      while (remaining.Any())
      {
        var shortest = double.MaxValue;
        Point next = null;
        foreach (var p in remaining)
        {
          var d = Distance(route.Last(), p);
          if (d < shortest)
          {
            shortest = d;
            next = p;
          }
        }
        route.Add(next);
        numericRoute.Add(_cities.IndexOf(next));
        remaining.Remove(next);
        distance += shortest;
    
      }


      distance += Distance(route.First(), route.Last());
      Console.WriteLine("Distance calculated in closestneighbour: " + distance);
      return numericRoute.ToArray();
    }
        /// <summary>
        /// Starts the clustering.
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="fusion"></param>
        /// <param name="metric"></param>
        /// <returns></returns>
        protected internal Cluster[] Cluster(List<Element> elements, Fusion fusion, IDistanceMetric metric)
        {
            HashSet<Cluster> clusters = new HashSet<Cluster>();
            ClusterPairs pairs = new ClusterPairs();

            // 1. Initialize each element as a cluster
            foreach (Element el in elements)
            {
                Cluster cl = new Cluster(fusion);
                cl.AddElement(el);
                clusters.Add(cl);
            }

            // 2. a) Calculate the distances of all clusters to all other clusters
            foreach (Cluster cl1 in clusters)
            {
                foreach (Cluster cl2 in clusters)
                {
                    if (cl1 == cl2)
                        continue;

                    ClusterPair pair = new ClusterPair(cl1, cl2, cl1.CalculateDistance(cl2));

                    pairs.AddPair(pair);
                }
            }

            // 2. b) Initialize the pair with the lowest distance to each other.
            ClusterPair lowestDistancePair = pairs.LowestDistancePair;

            // 3. Merge clusters to new clusters and recalculate distances in a loop until there are only countCluster clusters
            while (!isFinished(clusters, lowestDistancePair))
            {
                // a) Merge: Create a new cluster and add the elements of the two old clusters
                lowestDistancePair = pairs.LowestDistancePair;

                Cluster newCluster = new Cluster(fusion);
                newCluster.AddElements(lowestDistancePair.Cluster1.GetElements());
                newCluster.AddElements(lowestDistancePair.Cluster2.GetElements());

                // b)Remove the two old clusters from clusters
                clusters.Remove(lowestDistancePair.Cluster1);
                clusters.Remove(lowestDistancePair.Cluster2);

                // c) Remove the two old clusters from pairs
                pairs.RemovePairsByOldClusters(lowestDistancePair.Cluster1, lowestDistancePair.Cluster2);

                // d) Calculate the distance of the new cluster to all other clusters and save each as pair
                foreach (Cluster cluster in clusters)
                {
                    ClusterPair pair = new ClusterPair(cluster, newCluster, cluster.CalculateDistance(newCluster));
                    pairs.AddPair(pair);
                }

                // e) Add the new cluster to clusters
                clusters.Add(newCluster);
            }

            return clusters.ToArray<Cluster>();
        }
        public int LengthOfLongestSubstring(string s)
        {
            if (string.IsNullOrEmpty(s))
                return 0;

            char[] sArrays = s.ToCharArray();

            int backPointer = 0;
            int result = 0;
            HashSet<char> hs = new HashSet<char>();

            for (int frontPointer = 0; frontPointer < s.Length; )
            {
                while (frontPointer < s.Length && !hs.Contains(sArrays[frontPointer]))
                {
                    hs.Add(sArrays[frontPointer++]);
                }

                result = Math.Max(result, frontPointer - backPointer);
                while (frontPointer < s.Length && sArrays[backPointer] != sArrays[frontPointer])
                {
                    hs.Remove(sArrays[backPointer++]);
                }

                if (backPointer <= frontPointer && backPointer < s.Length)
                {
                    hs.Remove(sArrays[backPointer++]);
                }
            }

            return result;
        }
Example #10
0
 // HACK: HashSet parameter is ugly
 public static IEnumerable<string> FindFreeVariablesInLambda(IEnumerable<string> parameters, IEnumerable<object> body, HashSet<string> localVariablesDefinedInLambda)
 {
     HashSet<string> accessedVariables = new HashSet<string>();
     foreach (object o in body) FindAccessedVariables(o, accessedVariables, localVariablesDefinedInLambda);
     accessedVariables.Remove("nil");
     foreach (string p in parameters) accessedVariables.Remove(p);
     foreach (string i in localVariablesDefinedInLambda) accessedVariables.Remove(i);
     return accessedVariables;
 }
Example #11
0
        public Node[] FindPath()
        {
            HashSet<Node> open = new HashSet<Node>();
            HashSet<Node> closed = new HashSet<Node>();

            Node current = start;
            current.G = 0;

            Node destination = finish;

            current.F = HeuristicCost(current, destination);
            open.Add(current);

            while (open.Count != 0)
            {
                current = Lowest_f(open);
                if (current.Equals(destination))
                {
                    if (current.previous != null)
                    {
                        return Path(current, start);
                    }

                }

                open.Remove(current);
                closed.Add(current);

                foreach (Node node in GetNeighbours(current))
                {
                    double t = current.G + Distance(current, node);

                    if (t < node.G)
                    {
                        if (open.Contains(node))
                        {
                            open.Remove(node);
                        }
                        if (closed.Contains(node))
                        {
                            closed.Remove(node);
                        }
                    }

                    if (!open.Contains(node) && !(closed.Contains(node)))
                    {
                        node.G = t;
                        node.F = HeuristicCost(node, destination);
                        node.previous = current;
                        open.Add(node);
                    }
                }
            }
            return null;
        }
        internal static void Main()
        {
            string decorationLine = new string('-', Console.WindowWidth);
            Console.Write(decorationLine);
            Console.WriteLine("***Presenting the functionality of the data structure 'Hash set'***");
            Console.Write(decorationLine);

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

            Console.WriteLine("---Add operation---");
            years.Add(1990);
            years.Add(1992);
            years.Add(2013);
            years.Add(2016);
            years.Add(2022);
            Console.WriteLine("Count = " + years.Count);
            Console.WriteLine();

            Console.WriteLine("---Iterator functionality---");
            PrintYears(years);
            Console.WriteLine();

            Console.WriteLine("---Contains operation---");
            Console.WriteLine("Does years set contain {0}? - {1}", 1992, years.Contains(1992));
            Console.WriteLine("Does years set contain {0}? - {1}", 2012, years.Contains(2012));
            Console.WriteLine();

            Console.WriteLine("---Remove operation---");
            Console.WriteLine("Is {0} removed from years set? - {1}", 1996, years.Remove(1996));
            Console.WriteLine("Years set count: " + years.Count);
            Console.WriteLine("Is {0} removed from years set? - {1}", 1990, years.Remove(1990));
            Console.WriteLine("Years set count: " + years.Count);
            Console.WriteLine();

            Console.WriteLine("---UnionWith operation---");
            int[] yearsToUnionWith = new int[] { 2005, 2009, 2021, 2016, 1992, 2013 };
            years.UnionWith(yearsToUnionWith);
            Console.WriteLine("All years after a union with: {0}", string.Join(", ", yearsToUnionWith));
            PrintYears(years);
            Console.WriteLine("Years set count: " + years.Count);
            Console.WriteLine();

            Console.WriteLine("---IntersectWith operation---");
            int[] yearsToIntersectWith = new int[] { 2045, 2025, 2021, 2016, 1999, 2017, 2013 };
            years.IntersectWith(yearsToIntersectWith);
            Console.WriteLine("All years after an intersect with: {0}", string.Join(", ", yearsToIntersectWith));
            PrintYears(years);
            Console.WriteLine("Years set count: " + years.Count);
            Console.WriteLine();

            Console.WriteLine("---Clear operation---");
            years.Clear();
            Console.WriteLine("Years count after clearing: " + years.Count);
        }
Example #13
0
        private AppMetadata(string json)
        {
            JsonValue data;
            try
            {
                data = JsonValue.Parse(json);
            }
            catch (FormatException e)
            {
                MessageBox.Show("Apparently the metadata contains an error. Sorry about that! Please try again in a minute.\n\nThe error is: " + e.Message, "Error in apps.json", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
                return;
            }

            if ((int) data["version"] != 1)
            {
                MessageBox.Show("This version of Steam Disk Saver is too old. The metadata uses format " + data["version"] + ", but this version only supports format 1. Please download the latest version.", "Outdated version", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Environment.Exit(0);
            }

            foreach (var item in data["categories"])
            {
                Categories.Add(new Category(item.Key, item.Value));
            }

            var engines = data["engines"];

            foreach (var item in data["apps"])
            {
                var id = int.Parse(item.Key);
                var app = item.Value;

                Known.Add(id);

                var categoriesInApp = new HashSet<string>();
                foreach (var cat in app)
                {
                    categoriesInApp.Add(cat.Key);
                }

                categoriesInApp.Remove("engine");

                foreach (var cat in Categories)
                {
                    categoriesInApp.Remove(cat.Key);
                    cat.AddApp(id, app, engines);
                }

                foreach (var cat in categoriesInApp)
                {
                    Debug.WriteLine("Unknown category {0} in {1}", cat, id);
                }
            }
        }
Example #14
0
        // Method establishes which values can fill an empty square by eliminating any values already occurring in row/column/box.
        public List<int> DetermineValidOptionsForSquare(SquareCoordinate squareCoordinate, IImmutableSudokuGrid grid)
        {
            HashSet<int> validSquareOptions = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            for (int offset = 1; offset < 9; offset++)
            {
                validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row + offset) % 9, squareCoordinate.Column]);
                validSquareOptions.Remove(grid.Elements[(squareCoordinate.Row), (squareCoordinate.Column + offset) % 9]);
                validSquareOptions.Remove(grid.Elements[(3 * (squareCoordinate.Row / 3)) + offset % 3, (3 * (squareCoordinate.Column / 3)) + (offset - offset % 3) / 3]);
            }

            return validSquareOptions.ToList<int>();
        }
        public override Card[] RequestExhangeCards()
        {
            List<Card> retCards = new List<Card>();

            //arrange he cards by suits
            List<Card>[] suitsCount = ArrangeCardBySuits(Cards);

            //look at each suit which has 2 cards or less and add those cards to the returned array
            foreach (List<Card> suit in suitsCount)
            {
                if (suit.Count <= 2)
                {
                    retCards.AddRange(suit);
                    suit.Clear();
                }
            }

            //see how many cards are in the returned array
            if (retCards.Count == 3)
            {
                return retCards.ToArray();
            }
            else if (retCards.Count > 3)
            {
                //find lowest card and throw away
                while (retCards.Count > 3)
                {
                    //remove the card with the lowest value - till we have only 3 cards left
                    Card current = GetLowestCardInCollection(retCards);
                    retCards.Remove(current);
                }
            }
            else if (retCards.Count < 3)
            {
                //copy cards for operation & remove cards already picked from that collection
                ICollection<Card> cards_cpy = new HashSet<Card>(Cards);
                foreach (Card c in retCards)
                {
                    cards_cpy.Remove(c);
                }

                //add highest card in my hand to return array - till I have 3 cards
                while (retCards.Count < 3)
                {

                    Card current = GetHighestCardInCollection(cards_cpy);
                    retCards.Add(current);
                    cards_cpy.Remove(current);
                }
            }

            return retCards.ToArray();
        }
Example #16
0
        public static IEnumerable<Cluster<Word>> GenerateCognateSets(this CogProject project, Meaning meaning)
        {
            var words = new HashSet<Word>();
            var noise = new HashSet<Word>();
            foreach (VarietyPair vp in project.VarietyPairs)
            {
                WordPair wp;
                if (vp.WordPairs.TryGetValue(meaning, out wp))
                {
                    if (wp.Cognacy)
                    {
                        words.Add(wp.Word1);
                        words.Add(wp.Word2);
                        noise.Remove(wp.Word1);
                        noise.Remove(wp.Word2);
                    }
                    else
                    {
                        if (!words.Contains(wp.Word1))
                            noise.Add(wp.Word1);
                        if (!words.Contains(wp.Word2))
                            noise.Add(wp.Word2);
                    }
                }
            }

            double min = double.MaxValue;
            var distanceMatrix = new Dictionary<UnorderedTuple<Word, Word>, double>();
            Word[] wordArray = words.ToArray();
            for (int i = 0; i < wordArray.Length; i++)
            {
                for (int j = i + 1; j < wordArray.Length; j++)
                {
                    Word w1 = wordArray[i];
                    Word w2 = wordArray[j];
                    double score = 0;
                    WordPair wp;
                    if (w1.Variety != w2.Variety && w1.Variety.VarietyPairs[w2.Variety].WordPairs.TryGetValue(meaning, out wp) && wp.Cognacy
                        && wp.GetWord(w1.Variety) == w1 && wp.GetWord(w2.Variety) == w2)
                    {
                        score = wp.PredictedCognacyScore;
                    }
                    double distance = 1.0 - score;
                    min = Math.Min(min, distance);
                    distanceMatrix[UnorderedTuple.Create(w1, w2)] = distance;
                }
            }

            var clusterer = new FlatUpgmaClusterer<Word>((w1, w2) => distanceMatrix[UnorderedTuple.Create(w1, w2)], (1.0 + min) / 2);
            return clusterer.GenerateClusters(words).Concat(new Cluster<Word>(noise, true));
        }
Example #17
0
        public async Task<IEnumerable<Album>> AlbumsFromCommaSeparatedValuesAndUserId(string albumsAsCommaSeparatedValues, string userId)
        {
            if (string.IsNullOrWhiteSpace(albumsAsCommaSeparatedValues))
            {
                return Enumerable.Empty<Album>();
            }

            var albumsValues = new HashSet<string>();

            albumsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList()
                .ForEach(val =>
                {
                    albumsValues.Add(val.Trim());
                });

            var resultAlbum = await this.albums
                .All()
                .Where(a => (albumsValues.Contains(a.Name.ToLower()) ||
                                albumsValues.Contains(a.Id.ToString())) &&
                            a.Creator.Id == userId)
                .ToListAsync();

            (await this.albums
              .All()
              .Where(a => (albumsValues.Contains(a.Name.ToLower()) ||
                                albumsValues.Contains(a.Id.ToString())) &&
                            a.Creator.Id == userId)
              .Select(a => a.Name.ToLower())
              .ToListAsync())
              .ForEach(a => albumsValues.Remove(a));

            var idValues = new List<string>();

            albumsValues.ForEach(v =>
            {
                int id;
                var isId = int.TryParse(v, out id);
                if (isId)
                {
                    idValues.Add(v);
                }
            });

            idValues.ForEach(a => albumsValues.Remove(a));

            albumsValues.ForEach(tagName => resultAlbum.Add(new Album() { Name = tagName }));

            return resultAlbum;
        }
Example #18
0
        public static List<NavigationItem> GetNavigationItems(Func<string, string> resolveUrl = null,
            Func<NavigationItemAttribute, bool> filter = null)
        {
            var result = new List<NavigationItem>();
            var menuItems = GetNavigationItemAttributes(filter);
            var remaining = new HashSet<string>();
            foreach (var item in menuItems)
                remaining.Add(item.Key);

            Action<List<NavigationItem>, NavigationItemAttribute> processMenu = null;
            processMenu = (parent, menu) =>
            {
                var path = (menu.Category.IsEmptyOrNull() ? "" : (menu.Category + "/"));
                path += (menu.Title.TrimToNull() ?? "");
                remaining.Remove(path);

                var section = new NavigationItem
                {
                    Title = menu.Title,
                    Url = (!string.IsNullOrEmpty(menu.Url) && resolveUrl != null) ? resolveUrl(menu.Url) : menu.Url,
                    IconClass = menu.IconClass.TrimToNull(),
                    Target = menu.Target.TrimToNull()
                };

                bool isAuthorizedSection = !menu.Url.IsEmptyOrNull() &&
                    (menu.Permission.IsEmptyOrNull() || Authorization.HasPermission(menu.Permission));

                var children = menuItems[path];
                foreach (var child in children)
                    processMenu(section.Children, child);

                if (section.Children.Count > 0 || isAuthorizedSection)
                    parent.Add(section);
            };

            remaining.Remove("");
            foreach (var menu in menuItems[""])
                processMenu(result, menu);

            while (remaining.Count > 0)
            {
                var first = remaining.First();
                remaining.Remove(first);
                var menu = new NavigationMenuAttribute(Int32.MaxValue, first);
                processMenu(result, menu);
            }

            return result;
        }
 private int getLength(HashSet<int> hs, int cur)
 {
     int len = 1, left = cur - 1, right = cur + 1;
     while (hs.Contains(left))
     {
         ++len;
         hs.Remove(left--);
     }
     while (hs.Contains(right))
     {
         ++len;
         hs.Remove(right++);
     }
     return len;
 }
        ///<summary>Gets all files that indirectly depend on the specified file.</summary>
        public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName)
        {
            HashSet<GraphNode> visited;
            fileName = Path.GetFullPath(fileName);
            using (await rwLock.ReadLockAsync())
            {
                GraphNode rootNode;
                if (!nodes.TryGetValue(fileName, out rootNode))
                    return Enumerable.Empty<string>();

                var stack = new Stack<GraphNode>();
                stack.Push(rootNode);
                visited = new HashSet<GraphNode> { rootNode };
                while (stack.Count > 0)
                {
                    foreach (var child in stack.Pop().Dependents)
                    {
                        if (!visited.Add(child)) continue;
                        stack.Push(child);
                    }
                }
                // Don't return the original file.
                visited.Remove(rootNode);
            }
            return visited.Select(n => n.FileName);
        }
Example #21
0
        public StockActor(string stockSymbol)
        {
            _stockSymbol = stockSymbol;
            _subscribers = new HashSet<IActorRef>();

            _priceLookupChild = Context.ActorOf(Context.DI().Props<StockPriceLookupActor>());

            Receive<SubscribeToNewStockPricesMessage>(message => _subscribers.Add(message.Subscriber));
            Receive<UnSubscribeFromNewStockPricesMessage>(message => _subscribers.Remove(message.Subscriber));

            Receive<RefreshStockPriceMessage>(message => _priceLookupChild.Tell(message));

            Receive<UpdatedStockPriceMessage>(message =>
            {
                _stockPrice = message.Price;

                var stockPriceMessage = new StockPriceMessage(_stockSymbol, _stockPrice, message.Date);

                foreach (var subscriber in _subscribers)
                {
                    subscriber.Tell(stockPriceMessage);
                }
            });

        }
Example #22
0
 public override bool Control( GameEntity control, TimeSpan gameTime, Microsoft.Xna.Framework.Input.KeyboardState keyState )
 {
     if ( control is Projectile )
     {
         HashSet<Tank> tanks = new HashSet<Tank>();
         if ( control.Variables.ContainsKey( "Hypnotize" ) )
         {
             tanks = ( ( HashSet<Tank> )control.Variables[ "Hypnotize" ] );
         }
         if ( Vector2.Distance( control.Position, Owner.Position ) < rad )// && !Tools.IsGoingTowardsMe( Owner.Position, control.Angle, control.Position ) )
         {
             if ( !control.Variables.ContainsKey( "Hypnotize" ) || !tanks.Contains( Owner ) )
             {
                 DeflectorController d = new DeflectorController( Tools.Angle( Owner.Position, control.Position ) );
                 control.AppendController( d );
                 tanks.Add( Owner );
             }
         }
         else
         {
             tanks.Remove( Owner );
         }
         control.Variables[ "Hypnotize" ] = tanks;
     }
     return base.Control( control, gameTime, keyState );
 }
        /// <summary>
        /// Determines whether the interpreter factory contains the specified
        /// modules.
        /// </summary>
        /// <returns>The names of the modules that were found.</returns>
        public static async Task<HashSet<string>> FindModulesAsync(this IPythonInterpreterFactory factory, params string[] moduleNames) {
            var withDb = factory as PythonInterpreterFactoryWithDatabase;
            if (withDb != null && withDb.IsCurrent) {
                var db = withDb.GetCurrentDatabase();
                var set = new HashSet<string>(moduleNames.Where(m => db.GetModule(m) != null));
                return set;
            }

            var expected = new HashSet<string>(moduleNames);

            if (withDb != null) {
                var paths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(withDb.DatabasePath) ??
                    await PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync(withDb.Configuration.InterpreterPath).ConfigureAwait(false);
                var db = PythonTypeDatabase.GetDatabaseExpectedModules(withDb.Configuration.Version, paths)
                    .SelectMany()
                    .Select(g => g.ModuleName);
                expected.IntersectWith(db);
                return expected;
            }

            return await Task.Run(() => {
                var result = new HashSet<string>();
                foreach (var mp in ModulePath.GetModulesInLib(factory)) {
                    if (expected.Count == 0) {
                        break;
                    }

                    if (expected.Remove(mp.ModuleName)) {
                        result.Add(mp.ModuleName);
                    }
                }
                return result;
            });
        }
Example #24
0
 //build tree and track the leastcostleaf node;
 public bool BuildTree(PlanNode parent, HashSet<Action> actionList, Dictionary<string, object> goalState, PlanNode leastCostLeaf)
 {
     bool hasPath = false;
     foreach (Action a in actionList) {
         if (AreConditionsInState (a.preconditions, parent.currentState)) {
             Dictionary<string, object> newState = CreateStateWithEffects (a.effects, parent.currentState);
             PlanNode newNode = new PlanNode (parent, parent.totalCost + a.cost, newState, a);
             if (AreConditionsInState (goalState, newState)) {
                 if (leastCostLeaf == null) {
                     leastCostLeaf = newNode;
                 } else if (newNode.totalCost < leastCostLeaf.totalCost) {
                     leastCostLeaf = newNode;
                 }
                 hasPath = true;
             } else {
                 //remove the current action from list of available actions and build tree based on remaining actions
                 HashSet<Action> actionsMinusOne = new HashSet<Action> (actionList);
                 actionsMinusOne.Remove (a);
                 //if any path was found, set to true
                 hasPath = hasPath || BuildTree (newNode, actionsMinusOne, goalState, leastCostLeaf);
             }
         }
     }
     return hasPath;
 }
		public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo)
		{
			//modules do no have names/IDs, but genrally the only reason they exist
			//is because they have additional, optional dependencies
			//so find the dependencies that are not referenced in other modules
			//and use one as the label
			var module = (ModuleDescription)dataObject;
			var deps = new HashSet<string> ();
			foreach (Dependency dep in module.Dependencies) {
				deps.Add (dep.Name);
			}

			foreach (ModuleDescription other in module.ParentAddinDescription.AllModules) {
				if (other == module) {
					continue;
				}
				foreach (Dependency dep in other.Dependencies) {
					deps.Remove (dep.Name);
				}
			}

			if (deps.Count > 0) {
				nodeInfo.Label = deps.First ().Split (new[] { ' '})[0];
			} else {
				nodeInfo.Label = "Module";
			}
		}
		internal override bool FixElement(XElement rt, FwDataFixer.ErrorLogger logger)
		{
			var classAttr = rt.Attribute("class");
			if (classAttr == null)
				return true; // bizarre, but leave it alone
			List<string> requiredFields;
			if (!m_customFields.TryGetValue(classAttr.Value, out requiredFields))
				return true; // has no custom fields we care about
			var missingFields = new HashSet<string>(requiredFields);
			foreach (var child in rt.Elements())
			{
				if (child.Name == "Custom")
				{
					var nameAttr = child.Attribute("name");
					if (nameAttr != null)
						missingFields.Remove(nameAttr.Value); // not missing, we don't need to add it.
				}
			}
			foreach (var fieldName in missingFields)
			{
				rt.Add(new XElement("Custom",
					new XAttribute("name", fieldName),
					new XAttribute("val", "0")));
				var guid = rt.Attribute("guid").Value;
				// This is such an insignificant fix from the user's point of view that we might prefer not
				// even to report it. But don't remove the logging without adding another mechanism for
				// the system to know that a problem has been fixed...this controls the important behavior
				// of re-splitting the file before we commit.
				logger(guid, DateTime.Now.ToShortDateString(),
					String.Format(Strings.ksAddingMissingDefaultForValueType, guid));
			}
			return true;
		}
Example #27
0
        private static double FindMinimalCost(HashSet<ISet<int>> allTrees)
        {
            // Kruskal -> Sorting edges by their weight
            Array.Sort(paths, (a, b) => a.Item3.CompareTo(b.Item3));

            double result = 0;

            foreach (var path in paths)
            {
                var tree1 = allTrees.Where(tree => tree.Contains(path.Item1)).First();
                var tree2 = allTrees.Where(tree => tree.Contains(path.Item2)).First();

                // Elements are in same tree
                if (tree1.Equals(tree2)) continue;

                result += path.Item3;

                tree1.UnionWith(tree2);
                allTrees.Remove(tree2);

                // Small optimization
                if (allTrees.Count == 1) break;
            }

            return result;
        }
Example #28
0
        public static string Travelse(List<List<int>> graph)
        {
            var visited = new HashSet<int>();
            var planned = new HashSet<int>();
            var candidates = new Stack<int>();

            candidates.Push(0);
            planned.Add(0);
            var resultBuilder = new StringBuilder();
            while (candidates.Count > 0)
            {
                var currentVisited = candidates.Pop();
                planned.Remove(currentVisited);
                visited.Add(currentVisited);

                resultBuilder.Append(currentVisited);

                foreach (var vertex in graph[currentVisited])
                {
                    if (!visited.Contains(vertex) && !planned.Contains(vertex))
                    {
                        candidates.Push(vertex);
                        planned.Add(vertex);
                    }
                }

            }
            return resultBuilder.ToString();
        }
Example #29
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;
    }
        public static IEnumerable<string> GetBaseTypeAndInterfacesFullNames(this Type type)
        {
            Queue<Type> typesToSearch = new Queue<Type>();
            HashSet<string> typeNames = new HashSet<string>();

            typesToSearch.Enqueue(type);

            while(typesToSearch.Count > 0)
            {
                Type currentType = typesToSearch.Dequeue();

                if (typeNames.Contains(currentType.FullName))
                    continue; // Skip types we have already searched

                typeNames.Add(currentType.FullName);

                if(currentType.BaseType != null)
                {
                    typesToSearch.Enqueue(currentType.BaseType);
                }

                foreach(var @interface in currentType.GetInterfaces())
                {
                    typesToSearch.Enqueue(@interface);
                }
            }

            typeNames.Remove(type.FullName);

            return typeNames;
        }