/// <summary> /// Locates the changes between the prior and post state of the modules.. /// </summary> /// <param name="modules_prior">List of the available modules prior to the update.</param> /// <param name="modules_post">List of the available modules after the update.</param> private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post) { var prior = new HashSet<CkanModule>(modules_prior, new NameComparer()); var post = new HashSet<CkanModule>(modules_post, new NameComparer()); var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer())); var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer())); var unchanged = post.Intersect(prior);//Default compare includes versions var updated = post.Except(unchanged).Except(added).Except(removed).ToList(); // Print the changes. user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count()); if (added.Count > 0) { PrintModules("New modules [Name (CKAN identifier)]:", added); } if (removed.Count > 0) { PrintModules("Removed modules [Name (CKAN identifier)]:", removed); } if (updated.Count > 0) { PrintModules("Updated modules [Name (CKAN identifier)]:", updated); } }
string Main() { int position = 1; int smallGap = 2; int bigGap = 4; int totalPrimeCount = 0; HashSet<int> diagonals = new HashSet<int>(); diagonals.Add(1); while (true) { for (int i = 0; i < 4; i++) { position += smallGap; diagonals.Add(position); if (UsefulFunctions.IsPrime(position)) totalPrimeCount++; } double average = (double)totalPrimeCount / diagonals.Count(); if (average < .10) { break; } smallGap += 2; bigGap += 2; } return (bigGap - 1).ToString(); }
public ICollection<AuthorModel> GetRandomAuthors(int rightAuthorId) { var authorIds = this.data.Authors .All() .Select(a => a.Id) .ToList(); var randomAuthorIds = new HashSet<int>(); randomAuthorIds.Add(rightAuthorId); while (randomAuthorIds.Count() < GlobalConstants.NumberOfAuthorsToChoose) { var randomAuthorId = this.GetRandomAuthorId(authorIds); randomAuthorIds.Add(randomAuthorId); } var randomAuthors = this.data.Authors .All() .Where(a => randomAuthorIds.Contains(a.Id)) .OrderBy(a => a.FullName) .ProjectTo<AuthorModel>() .ToList(); return randomAuthors; }
static void Main(string[] args) { string input = Console.ReadLine(); string pattern = @"(\D+)(\d+)"; var regex = new Regex(pattern); MatchCollection matches = Regex.Matches(input,pattern); StringBuilder builder = new StringBuilder(); foreach (Match match in matches) { StringBuilder sb = new StringBuilder(); var message = match.Groups[1].Value.ToUpper(); var numberOfRepetitions = int.Parse(match.Groups[2].Value); for (int i = 0; i < numberOfRepetitions; i++) { sb.Append(message); } builder.Append(sb); } var set = new HashSet<char>(); foreach (char ch in builder.ToString()) { set.Add(ch); } Console.WriteLine("Unique symbols used: {0}", set.Count()); Console.WriteLine(builder); }
public HashSet<String> extract() { HashSet<String> hashes = new HashSet<String>(); int totalCount = 0; uint maxMemoryChunk = 10 * 1024 * 1024; // 10 megabytes byte[] buffer = new byte[maxMemoryChunk]; while (true) { int bytesRead = reader.readNextMemoryRegion(buffer, maxMemoryChunk); if (0 == bytesRead) { Console.WriteLine("Finished reading all regions"); break; } int n = bytesRead - 8; for (int i = 0; i < bytesRead; ++i) { if ('s' == buffer[i] && isMagic(buffer, i, server.Magic)) { totalCount++; hashes.Add(BitConverter.ToString(buffer, i + 8, 32).ToLower().Replace("-", "")); } } } Console.WriteLine("Number of unique s2gs hash strings found: " + hashes.Count()); Console.WriteLine("Number of total s2gs hash strings found: " + totalCount); return hashes; }
public override void UndoRedoPerformed(List<GameObject> modified) { modifiedMeshes = new HashSet<Mesh>(modifiedMeshes.Where(x => x != null)); if(z_ReflectionUtil.ProBuilderExists()) { // delete & undo causes cases where object is not null but the reference to it's pb_Object is HashSet<object> remove = new HashSet<object>(); foreach(object pb in modifiedPbMeshes) { try { z_ReflectionUtil.Invoke(pb, "ToMesh"); z_ReflectionUtil.Invoke(pb, "Refresh"); z_ReflectionUtil.Invoke(null, z_Pref.PB_EDITOR_MESH_UTILITY_TYPE, "Optimize", BindingFlags.Public | BindingFlags.Static, z_Pref.PB_EDITOR_ASSEMBLY, pb); } catch { remove.Add(pb); } } if(remove.Count() > 0) modifiedPbMeshes.SymmetricExceptWith(remove); } foreach(Mesh m in modifiedMeshes) m.vertices = m.vertices; base.UndoRedoPerformed(modified); }
public static void problem(int[] numbers, int raznica) { HashSet<int> lilu = new HashSet<int>(numbers); int counter = lilu .Count(p => lilu.Contains(p + raznica)); Console.WriteLine(counter); }
private void textBox1_TextChanged(object sender, EventArgs e) { //Unsorted HashSet<int> set = new HashSet<int>(); List<int> list = new List<int>(); SortedSet<int> sortset = new SortedSet<int>(); StringBuilder s = new StringBuilder(); Random rand = new Random(); //Add random numbers to a list (not ordered) for (int i = 0; i < 10000; i++) { list.Add(rand.Next(1, 20000)); } //Place unique numbers from the list previously generated into a hashset for (int i = 0; i < 10000; i++) { set.Add(list[i]); } //Sorts the list of random numbers through the use of a Sortedset for (int i = 0; i < 10000; i++) { sortset.Add(list[i]); } //count distinct characters in the list int unique = (from i in list select i).Distinct().Count(); //String formatting s.Append("1. Hashset method: " + set.Count().ToString() + " unique numbers." + "The time complexity of this code is O(nlog(n) + 2n), because the intialization of variables " + "is O(1) and the add function for the hashset and list is O(1). Therefore the algorithm executes" + "10000 times twice and we'll mark this up to be (2n)." + "This gives us a time complexity for the aglorithm to be O(2n). Then the add time complexity for the sortedset is nlogn which consequatnly"+ "gives us O(nlog(n) + 2n)"); s.Append("\r\n2. " + unique.ToString() + " unique numbers."); s.Append("\r\n3. " + sortset.Count().ToString() + " unique numbers"); textBox1.Text = s.ToString(); }
public void TestEdbLogging() { Init(); var queryArgs = new Dictionary<string, string> { { "@source.environment", TestName }, { "@source.groupId", CurrentGroupId }, { "@source.path", "EDB_expected_event_sources.log" } }; var expectedLines = File.ReadAllText(@"Expected\EdbLoggingTest.txt").Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var expected = new HashSet<string>(expectedLines); GetAndValidateRecords(queryArgs, new [] { "@message" }, expected.Count(), records => { foreach (var record in records) { var message = (JContainer)JsonConvert.DeserializeObject(record.Fields["@message"]); message.Children().First().Remove(); var lineText = JsonConvert.SerializeObject(message); Assert.IsTrue(expected.Contains(lineText)); } }, 3); }
public long Solve() { var primes = new Prime((long)Math.Sqrt(Limit) + 1).PrimeList; var squerePrimes = new List<long>(); var cubePrimes = new List<long>(); var fourthPrimes = new List<long>(); var cubeLimit = false; var fourthLimit = false; foreach (var prime in primes) { var squere = prime * prime; squerePrimes.Add(squere); if (!cubeLimit) { var cube = squere * prime; if (cube > Limit) { cubeLimit = true; continue; } cubePrimes.Add(cube); } if (!fourthLimit) { var fourth = squere * squere; if (fourth > Limit) { fourthLimit = true; continue; } fourthPrimes.Add(fourth); } } Console.WriteLine(squerePrimes.Count); Console.WriteLine(cubePrimes.Count); Console.WriteLine(fourthPrimes.Count); var numbers = new HashSet<long>(); foreach (var cubePrime in cubePrimes) { foreach (var squerePrime in squerePrimes) { foreach (var fourthPrime in fourthPrimes) { numbers.Add(cubePrime + squerePrime + fourthPrime); } } } return numbers.Count(t => t < Limit); }
public RearsegmentBackups(IEnumerable<Segment> segments, HashSet<NodeEndpoint> endpoints, int numberOfBackCopiesToKeep) { this.segments = segments; this.endpoints = endpoints; this.numberOfBackCopiesToKeep = numberOfBackCopiesToKeep; fairDistribution = (segments.Count() * numberOfBackCopiesToKeep) / endpoints.Count() + 1; currentDistribution = PrepareDistributions(); }
private static string GetRequestedByFromChangeset(IEnumerable<IBuildInformationNode> changesets) { var users = new HashSet<String>(); foreach (var changeset in changesets) users.Add(changeset.Fields["CheckedInBy"]); var count = users.Count(); if (count > 1) return "(Multiple Users)"; return users.First(); }
public void ShuffleDeck() { if (this.cards.Count() != 0) throw new Exception(); HashSet<int> indicesTaken = new HashSet<int>(); while (this.cards.Count() < allCards.Count) { int idxToTake = rng.Next(0, allCards.Count); if (!indicesTaken.Contains(idxToTake)) { this.cards.Push(allCards[idxToTake]); indicesTaken.Add(idxToTake); } } if (indicesTaken.Count() != allCards.Count) throw new Exception(); }
public long Solve() { var primes = new List<int> { 2, 3, 5, 7 }; var truncatePrimes = new HashSet<int>(); var posibleLeftPrimes = new List<int>(); var posibleRightPrimes = new List<int>(); while (truncatePrimes.Count() < 11) { } return 0; }
public bool IsConnected() { HashSet<Point> allPathablePoints = new HashSet<Point>(); foundPathablePoints = new HashSet<Point>(); for (int i = 0; i < thisMap.Width; i++) { for (int j = 0; j < thisMap.Height; j++) { if(CountsAsWalkable(thisMap.getCell(i, j))) allPathablePoints.Add(new Point(i, j)); } } if(allPathablePoints.Count() == 0) return true; Stack<Point> workNodes = new Stack<Point>(); workNodes.Push(allPathablePoints.First()); while (workNodes.Count() > 0) { var thisNode = workNodes.Pop(); if (CountsAsWalkable(thisMap.getCell(thisNode.x, thisNode.y))) { foundPathablePoints.Add(thisNode); var neighbours = Get4WayNeighbours(thisNode); foreach (var p in neighbours) workNodes.Push(p); } } if (allPathablePoints.Intersect(foundPathablePoints).Count() == allPathablePoints.Count()) return true; return false; }
double CalcAverage(HashSet<int> diagonals) { long totalCount = diagonals.Count(); int primeCount = 0; foreach (int diagonal in diagonals) { if (primes[diagonal]) primeCount++; } double average = (double)primeCount / totalCount; return average; }
private static IEnumerable<long> GetAllPermutation(long posiblePrime) { var output = new HashSet<long> { posiblePrime }; var count = 0; var posiblePrimeText = posiblePrime.ToString(CultureInfo.InvariantCulture); while (output.Count != count) { posiblePrimeText = GetNexPosible(posiblePrimeText); count = output.Count(); output.Add(int.Parse(posiblePrimeText)); } return output; }
private static ICollection<Student> SeedStudents() { ICollection<Student> students = new HashSet<Student>(); while (students.Count() <= 10) { students.Add( new Student( firstNames[rnd.Next(0, firstNames.Length)], lastNames[rnd.Next(0, lastNames.Length)], GenerateFacultyNumber(rnd) )); } return students; }
public void AddFeedWritesSourceIfItDoesNotExist() { // Arrange bool writeCalled = false; var sourceFile = GetPackagesSourceFile(); sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true); ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources()); // Act bool returnValue = PackageManagerModule.AddPackageSource(sourceFile.Object, set, new WebPackageSource(source: "http://www.microsoft.com/feed3", name: "Feed3")); // Assert Assert.Equal(set.Count(), 3); Assert.True(writeCalled); Assert.True(returnValue); }
public void CardsAreRandomlyDistributed() { // Arrange var cardPositions = new HashSet<int>(); // Act for(var i=0; i<400; i++) { Setup(); var firstCard = board.First(); var matchPosition = board.ToList().FindIndex(1, p => p.IsMatch(firstCard)); cardPositions.Add(matchPosition); } // Assert cardPositions.Count().ShouldBeGreaterThanOrEqualTo(numberOfPairs-1); }
public static void CompareSequenceLists(HashSet<string> expected, HashSet<string> result) { Console.WriteLine(); Console.Write("Expected (Possible): "); foreach (var value in expected) Console.Write(value + ","); Console.WriteLine(); Console.Write("Actual:"); foreach (var value in result) Console.Write(value + ","); Assert.AreEqual(expected.Count, result.Count(), "Different sequence counts."); foreach (var s in result) { Assert.IsTrue(expected.Contains(s), "Could not locate " + s); } }
private bool IsPandigital(long number) { var digits = new HashSet<long>(); while (number > 0) { var digit = number % 10; if (digit == 0) return false; digits.Add(digit); number = number / 10; } return digits.Count() == 9; }
public void Rete(HashSet<int> list, Stack<int> st, List<IList<int>> re) { if (list.Count() == 0) { re.Add(new List<int>(st)); return; } HashSet<int> nhs = new HashSet<int>(list); foreach (var item in list) { nhs.Remove(item); st.Push(item); Rete(nhs, st, re); st.Pop(); nhs.Add(item); } }
private bool IsPandigital(long number) { var lenght = (int)Math.Log10(number) + 1; var digits = new HashSet<long>(); while (number > 0) { var digit = number % 10; if (digit == 0) return false; digits.Add(digit); number = number / 10; } return (digits.Count() == lenght) && digits.Max() == lenght; }
public ActionResult Index() { var model = new HomeViewModel(); var randomQuestion = factory.GetRandomQuestion(); var authorIds = this.Data.Authors .All() .Select(a => a.Id) .ToList(); var randomAuthorIds = new HashSet<int>(); if (GlobalVariables.BinaryMode) { var randomAuthorId = factory.GetRandomAuthorId(authorIds); randomAuthorIds.Add(randomAuthorId); } else { randomAuthorIds.Add(randomQuestion.AuthorId); while (randomAuthorIds.Count() < GlobalConstants.NumberOfAuthorsToChoose) { var randomAuthorId = factory.GetRandomAuthorId(authorIds); randomAuthorIds.Add(randomAuthorId); } } var authors = this.Data.Authors .All() .Where(a => randomAuthorIds.Contains(a.Id)) .ProjectTo<AuthorViewModel>() .ToList() .OrderBy(a => a.FullName); model.Question = randomQuestion; model.Authors = authors; return View(model); }
internal IEnumerable<RepositoryCommitModel> GetTags(string name, int page, int p, out string referenceName, out int totalCount) { var commit = GetCommitByName(name, out referenceName); if (commit == null) { totalCount = 0; return Enumerable.Empty<RepositoryCommitModel>(); } var tags = _repository.Tags; var commits = new HashSet<RepositoryCommitModel>(AnonymousComparer.Create<RepositoryCommitModel>((x, y) => x.ID == y.ID, obj => obj.ID.GetHashCode())); foreach (var tag in tags) { var c = _repository.Lookup(tag.Target.Id) as Commit; commits.Add(ToModel(c)); } totalCount = commits.Count(); return commits.OrderByDescending(x => x, (x, y) => x.Date.CompareTo(y.Date)); }
public void TestAddAllAndForEach() { // Arrange var setA = new HashSet<int>(); setA.Add(1); setA.Add(2); setA.Add(3); var setB = new HashSet<int>(); setB.Add(2); setB.Add(4); setB.Add(6); var expectedValues = new int[] { 1, 2, 3, 4, 6 }; // Act setA.AddAll(setB); // Assert Assert.AreEqual(expectedValues.Length, setA.Count()); expectedValues.ForEach(expected => Assert.IsTrue(setA.Contains(expected))); }
public static void CompareSequenceLists(HashSet <string> expected, HashSet <string> result) { Console.WriteLine(); Console.Write("Expected (Possible): "); foreach (var value in expected) { Console.Write(value + ","); } Console.WriteLine(); Console.Write("Actual:"); foreach (var value in result) { Console.Write(value + ","); } Assert.AreEqual(expected.Count, result.Count(), "Different sequence counts."); foreach (var s in result) { Assert.IsTrue(expected.Contains(s), "Could not locate " + s); } }
public void GetHashCode_DuplicateTagHelpers_NoHashCodeCollisions() { // Arrange var tagHelpers = new List <TagHelperDescriptor>(); var tagHelpersPerBatch = -1; // Reads 5 copies of the TagHelpers (with 5x references) // This ensures we don't have any dependencies on reference based GetHashCode for (var i = 0; i < 5; ++i) { var tagHelpersBatch = ReadTagHelpers(TagHelpersTestFile.OpenRead()); tagHelpers.AddRange(tagHelpersBatch); tagHelpersPerBatch = tagHelpersBatch.Count; } // Act var hashes = new HashSet <int>(tagHelpers.Select(t => t.GetHashCode())); // Assert // Only 1 batch of taghelpers should remain after we filter by hash Assert.Equal(hashes.Count(), tagHelpersPerBatch); }
public static void Part1() { var inputStrings = File.ReadAllLines(inputFilePath); //var inputStrings = testInput; var rules = new List <BagRule>(); foreach (var ruleString in inputStrings) { var bagRule = new BagRule(ruleString); Console.WriteLine(bagRule); rules.Add(bagRule); } //Okay, now we've got the rules: var goalBag = "shiny gold"; var goalBags = new List <string>() { goalBag }; var bagsThatCouldContainGoalBag = new HashSet <string>(); while (goalBags.Count > 0) { var currentGoalBag = goalBags[0]; goalBags.RemoveAt(0); var bagsContainingGoalBag = GetBagsContainingGoalBag(rules, currentGoalBag); foreach (var bagContainingGoalBag in bagsContainingGoalBag) { bagsThatCouldContainGoalBag.Add(bagContainingGoalBag); } goalBags.AddRange(bagsContainingGoalBag); } Console.WriteLine(""); Console.WriteLine($"Could Contain Bags: {string.Join(", ", bagsThatCouldContainGoalBag)}"); Console.WriteLine($"Count: {bagsThatCouldContainGoalBag.Count()}"); }
// 执行用时: 132 ms, 在所有 C# 提交中击败了 39.58% 的用户 // 内存消耗: 27.7 MB, 在所有 C# 提交中击败了 100.00% 的用户 // Acknowledgement: This is a C#-version replicate of the [official solution](https://leetcode-cn.com/problems/contains-duplicate-ii/solution/cun-zai-zhong-fu-yuan-su-ii-by-leetcode/) public bool ContainsNearbyDuplicate(int[] nums, int k) { HashSet <int> numSet = new HashSet <int>(); for (int i = 0; i < nums.Length; i++) { int currentValue = nums[i]; if (numSet.Contains(currentValue)) { return(true); } numSet.Add(currentValue); if (numSet.Count() > k) { numSet.Remove(nums[i - k]); } } return(false); }
//Determine the first set for sym, where sym is the first element in the RHS of the rule public static HashSet <string> FirstOf(string sym, Dictionary <string, HashSet <string> > firsts, ProductionRule rule) { var first = firsts[sym]; if (first.Count() == 0 || first.Any(x => x == EPSILON)) { foreach (var rightElem in rule.Right.Where(x => x != sym)) { first = new HashSet <string>(first.Union(firsts[rightElem])); if (first.Count() == 0 || firsts[rightElem].Any(x => x == EPSILON)) { continue; } else { first.Remove(EPSILON); break; } } } return(first); }
static void Main(string[] args) { string filename = args[0]; string input = File.ReadAllText(filename); IRegex regex = Parser.Parse(input); Console.WriteLine($"Part1: {regex.GetLongestNonCyclicWord().Length}"); HashSet <string> validPaths = new HashSet <string>(); HashSet <string> allPaths = regex.GetNonCyclicWords().ToHashSet(); foreach (var path in allPaths) { for (int i = 1000; i <= path.Length; i++) { validPaths.Add(path.Substring(0, i)); } } Console.WriteLine(validPaths.Count()); Console.WriteLine(validPaths.Select(GetRoomCoordinates).ToHashSet().Count()); }
private static int[] removeDuplicates(int[] a) { HashSet <int> set = new HashSet <int>(); foreach (var item in a) { if (!set.Contains(item)) { set.Add(item); } } int len = set.Count(); int [] result = new int[len]; int i = 0; foreach (var item in set) { result[i++] = item; } return(result); }
public void PreparePostCount(IEnumerable <int> blogs) { var ids = new HashSet <int>(blogs); var result = new Dictionary <int, int>(ids.Count()); var postCountCache = _cache.Get <ConcurrentDictionary <int, int> >(CacheService.PostCountCacheKey) ?? new ConcurrentDictionary <int, int>(); var uncached = ids.Where(i => !postCountCache.ContainsKey(i)); if (uncached.Count() > 0) { var postCounts = _db.Posts.Where(u => uncached.Contains(u.ItemId) && u.IdType == ItemType.Blog) .GroupBy(p => p.ItemId).ToDictionary(u => u.Key, u => u.Count()); foreach (var id in uncached) { int count = 0; postCounts.TryGetValue(id, out count); postCountCache.TryAdd(id, count); } } _cache.Set(CacheService.PostCountCacheKey, postCountCache, new MemoryCacheEntryOptions { Priority = CacheItemPriority.High }); }
/// <summary> /// An Email has two parts, local name and domain name. /// Eg: rocky @usf.edu – local name : rocky, domain name : usf.edu /// Besides lowercase letters, these emails may contain '.'s or '+'s. /// If you add periods ('.') between some characters in the local name part of an email address, mail /// sent there will be forwarded to the same address without dots in the local name. /// For example, "*****@*****.**" and "*****@*****.**" forward to the same email address. (Note that this rule does not apply for domain names.) /// If you add a plus('+') in the local name, everything after the first plus sign will be ignored.This allows /// certain emails to be filtered, for example ro.cky+bulls @usf.com will be forwarded to rocky @email.com. (Again, this rule does not apply for domain names.) /// It is possible to use both of these rules at the same time. /// Given a list of emails, we send one email to each address in the list.Return, how many different addresses actually receive mails? /// Eg: /// Input: ["*****@*****.**","*****@*****.**","*****@*****.**"] /// Output: 2 /// Explanation: "*****@*****.**" and "*****@*****.**" actually receive mails /// </summary> /// <param name="emails"></param> /// <returns>The number of unique emails in the given list</returns> private static int UniqueEmails(List <string> emails) { try { /* * From the above explanation, it is understood that * 1. Local name should ignore "." * 2. If Local name has "+", everything after the first plus is to be ignored * 3. Both of the above rules doesnt apply for Domain name * Created a new hashset object lobjUniqueEmails to handle the Unique email addresses */ HashSet <String> lobjUniqueEmails = new HashSet <String>(); foreach (String email in emails) { //Removing the spaces if any provided in the input String lstrEmail = email.Replace(" ", ""); //Fetching the index of "@" to seperate the local name and domain name int i = lstrEmail.IndexOf('@'); String lstrLocalName = lstrEmail.Substring(0, i); String lstrDomainName = lstrEmail.Substring(i); //If Local name contains "+", terminate the later part of the string from plus sign if (lstrLocalName.Contains('+')) { lstrLocalName = lstrLocalName.Substring(0, lstrLocalName.IndexOf('+')); } //Remove the "." present in the local name lstrLocalName = lstrLocalName.Replace(".", ""); //Concatenate local and domain names and added it to the HashSet object to provide unique email addresses lobjUniqueEmails.Add(lstrLocalName + lstrDomainName); } //Return the count of unique email addresses return(lobjUniqueEmails.Count()); } catch (Exception e) { Console.WriteLine(e.Message); throw; } }
public static Dictionary <uint256, List <BalanceOperation> > GetOperationsPerTransactions(Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerAddresses) { // 1. Get all the unique operations var opSet = new HashSet <BalanceOperation>(); foreach (var elem in operationsPerAddresses) { foreach (var op in elem.Value) { opSet.Add(op); } } if (opSet.Count() == 0) { Program.Exit("Wallet has no history yet."); } // 2. Get all operations, grouped by transactions var operationsPerTransactions = new Dictionary <uint256, List <BalanceOperation> >(); foreach (var op in opSet) { var txId = op.TransactionId; List <BalanceOperation> ol; if (operationsPerTransactions.TryGetValue(txId, out ol)) { ol.Add(op); operationsPerTransactions[txId] = ol; } else { operationsPerTransactions.Add(txId, new List <BalanceOperation> { op }); } } return(operationsPerTransactions); }
public double get_direct_relevance(String text, String query, HashSet <String> query_content_words) { String[] query_category_words = get_category_words_of(query); String[] text_words = text.Split(); double score = 0.0; foreach (String word in text_words) { double category_score = 0.0, content_score = 0.0; foreach (String category_word in query_category_words) { category_score += get_word_similarity(word, category_word); } foreach (String content_word in query_content_words) { content_score += get_word_similarity(word, content_word); } score += category_score / Math.Pow(query_category_words.Count(), 0.5) + // 0.5 because length doesn't really matter content_score / Math.Pow(query_content_words.Count(), 1.0); // 1.0 as standard scaling power } return(score / Math.Pow(text_words.Count(), 1.5)); // 1.5 to penalize long sentences }
public static IServiceCollection InstallConfigurators(this IServiceCollection serviceCollection, Predicate <AssemblyName> assemblyMatch, Predicate <Type> typeMatch, Assembly rootAssembly = null) { if (rootAssembly == null) { rootAssembly = Assembly.GetCallingAssembly(); } var assemblies = new HashSet <Assembly> { rootAssembly }; AddReferencedAssemblyTree(rootAssembly, assemblyMatch, assemblies); if (assemblies.Count() < 1) { throw new ConfiguratorException("There were no assemblies found that match the predicate provided."); } serviceCollection.InstallConfigurators(assemblies, typeMatch); return(serviceCollection); }
public UnLockResult UnLock(string lockname) { lock (_lockerList) { if (_lockerList.Count(c => lockname == c.Name) == 0) { return(UnLockResult.NotExists); } } try { _client.deleteAsync($"/locks/{lockname}").Wait(); return(UnLockResult.Success); } catch (Exception) { //throw; } return(UnLockResult.Fail); }
public List <int> NumerosAleatorios() { Random ale = new Random(); HashSet <int> ListaAleatoriosCompleta = new HashSet <int>(); do { int a = ale.Next(1, 91); ListaAleatoriosCompleta.Add(a); } while (ListaAleatoriosCompleta.Count() < 90); List <int> aleatoriosDesordenados = new List <int>(); foreach (int i in ListaAleatoriosCompleta) { aleatoriosDesordenados.Add(i); } return(aleatoriosDesordenados); }
private static IEnumerable <IMethodReference> GetEntryPointsFromOptions(ILGarbageCollectorOptions options, WholeProgram wholeProgram) { ISet <IEntryPointDetector> entryPointDetectors = new HashSet <IEntryPointDetector>(); bool ignoreMainEntryPoints = false; if (options.entrypoints != null) { entryPointDetectors.Add(new DocCommentFileEntryPointDetector(options.entrypoints)); ignoreMainEntryPoints = true; } if (options.entryattributes != null) { entryPointDetectors.Add(new AttributeFileEntryPointDetector(options.entryattributes)); } // If no entrypoints were directly specified are used, we'll just get the entry points // from the main assemblies. if (!ignoreMainEntryPoints) { entryPointDetectors.Add(new RootAssembliesEntryPointDetector()); } ISet <IMethodReference> entryPoints = new HashSet <IMethodReference>(); foreach (IEntryPointDetector entryPointDetector in entryPointDetectors) { entryPoints.UnionWith(entryPointDetector.GetEntryPoints(wholeProgram)); } if (entryPoints.Count() == 0) { Console.WriteLine("Error: Could not find any entry points."); System.Environment.Exit(-1); } return(entryPoints); }
protected override IResult CheckCell(IMapCell cell) { Stack <IMapCell> stack = new Stack <IMapCell>(); ICollection <IMapCell> visitedCells = new HashSet <IMapCell>(); bool pacificConnected = false; bool atlanticConnectected = false; bool success = false; IMapCell startCell = cell; stack.Push(cell); while (stack.Count > 0) { visitedCells.Add(cell); IEnumerable <IMapCell> possibleNeighbours = GetPossibleNeighbours(cell, visitedCells); //There is more likely that higher neigbourhood will not be a dead end possibleNeighbours.OrderBy(n => n.Heigh).ToList().ForEach(pn => stack.Push(pn)); if (possibleNeighbours.Contains(_map.GetCell(0, 0))) { pacificConnected = true; TurnStackUpsideDown(ref stack); } if (possibleNeighbours.Contains(_map.GetCell(_map.SizeY - 1, _map.SizeX - 1))) { atlanticConnectected = true; TurnStackUpsideDown(ref stack); } if (pacificConnected && atlanticConnectected) { success = true; break; } cell = stack.Pop(); } return(new Result(startCell, visitedCells.Count(), success)); }
/// <summary> /// Update/Create current lucene index by paragraph id. Due to out-of-date /// </summary> /// <param name="updateID">An iterable contains all paragraph id should be updated</param> private void AddIndexFromID(HashSet <String> updateID, string indexMode) { isIndexing = true; totalCount = updateID.Count(); if (totalCount == 0) { progressRate = 1; } else { foreach (var id in updateID) { //if (isDebug) Console.WriteLine("Adding: " + id); lucene.DeleteDocumentByID(id); count += 1; progressRate = count / totalCount; try { if (indexMode == GlobalVar.IndexByParagraphMode) { IndexByParagraph(id); } else { IndexByDocument(id); } } catch (System.Runtime.InteropServices.COMException e) { int code = e.HResult; if (isDebug) { Console.WriteLine("Exception: Error Code is " + code); } } } } isIndexing = false; }
private void validateGene(int cityNum) { // check if the numbers of cities in the array equal the number of cities // that are required in the solution this.valid = true; if (this.gene.Length != cityNum) { this.valid = false; } // if they are equal, check for duplicates else { //var groups = this.gene.GroupBy(v => v); var groups = new HashSet <byte>(this.gene); if (groups.Count() != this.gene.Length) { //Console.WriteLine("GROUP: {0}", groups.Count()); //Console.WriteLine("GENE LENGTH: {0}", this.gene.Length); this.valid = false; } } }
public int UniqueMorseRepresentations(string[] words) { string[] morse = new string[] { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; HashSet <string> uniqueMappings = new HashSet <string>(); foreach (string word in words) { StringBuilder morseConversion = new StringBuilder(); foreach (char letter in word) { int alphabetIndex = (int)char.ToUpper(letter) - 64; string morseLetter = morse[alphabetIndex - 1]; morseConversion.Append(morseLetter); } uniqueMappings.Add(morseConversion.ToString()); } return(uniqueMappings.Count()); }
public string Execute(RouteSpecification routeSpec) { var routeNameBuilder = new StringBuilder(); if (routeSpec.AreaName.HasValue()) { routeNameBuilder.AppendFormat("{0}_", routeSpec.AreaName); } routeNameBuilder.Append(routeSpec.ControllerName); routeNameBuilder.AppendFormat("_{0}", routeSpec.ActionName); // Ensure route names are unique. var routeName = routeNameBuilder.ToString(); var routeNameIsRegistered = _registeredRouteNames.Contains(routeName); if (routeNameIsRegistered) { // Prefix with the first verb (assuming this is the primary verb) if not a GET route. if (routeSpec.HttpMethods.Length > 0 && !routeSpec.HttpMethods.Contains("GET")) { routeNameBuilder.AppendFormat("_{0}", routeSpec.HttpMethods.FirstOrDefault()); } // Suffixing with an index if necessary to disambiguate. routeName = routeNameBuilder.ToString(); var count = _registeredRouteNames.Count(n => n == routeName || n.StartsWith(routeName + "_")); if (count > 0) { routeNameBuilder.AppendFormat("_{0}", count); } } routeName = routeNameBuilder.ToString(); _registeredRouteNames.Add(routeName); return(routeName); }
static void Main(string[] args) { HashSet <int> uniqueWords = new HashSet <int>(); HashSet <int> rejectedWords = new HashSet <int>(); string sortedWord; int sortedHashCode; string userInput = Console.ReadLine(); string[] firstLine = userInput.Split(' '); int n = Int32.Parse(firstLine[0]); int k = Int32.Parse(firstLine[1]); char[] letters = new char[k]; for (int i = 0; i < n; i++) { userInput = Console.ReadLine(); letters = userInput.ToCharArray(); Array.Sort(letters); sortedWord = new string(letters); sortedHashCode = sortedWord.GetHashCode(); if (uniqueWords.Contains(sortedHashCode)) { uniqueWords.Remove(sortedHashCode); rejectedWords.Add(sortedHashCode); } else if (rejectedWords.Contains(sortedHashCode)) { continue; } else { uniqueWords.Add(sortedHashCode); } } Console.WriteLine(uniqueWords.Count()); }
private double GetMinimumCostRoute(int startVertex, HashSet<int> set, Node root) { if (!set.Any()) { //source node is assumed to be the first root.ChildNodes = new Node[1] { new Node { Value = _vertices.First(), Selected = true } }; return _adjacencyMatrix[startVertex, 0]; } double totalCost = double.MaxValue; int i = 0; int selectedIdx = i; root.ChildNodes = new Node[set.Count()]; foreach (var destination in set) { root.ChildNodes[i] = new Node { Value = destination }; double costOfVistingCurrentNode = _adjacencyMatrix[startVertex, destination]; var newSet = new HashSet<int>(set); newSet.Remove(destination); double costOfVisitingOtherNodes = GetMinimumCostRoute(destination, newSet, root.ChildNodes[i]); double currentCost = costOfVistingCurrentNode + costOfVisitingOtherNodes; if (totalCost > currentCost) { totalCost = currentCost; selectedIdx = i; } i++; } root.ChildNodes[selectedIdx].Selected = true; return totalCost; }
internal override void UndoRedoPerformed(List <GameObject> modified) { modifiedMeshes = new HashSet <PolyMesh>(modifiedMeshes.Where(x => x != null)); #if PROBUILDER_4_0_OR_NEWER if (ProBuilderBridge.ProBuilderExists()) { // delete & undo causes cases where object is not null but the reference to it's pb_Object is HashSet <GameObject> remove = new HashSet <GameObject>(); foreach (GameObject pb in modifiedPbMeshes) { try { ProBuilderBridge.ToMesh(pb); ProBuilderBridge.Refresh(pb); ProBuilderBridge.Optimize(pb); } catch { remove.Add(pb); } } if (remove.Count() > 0) { modifiedPbMeshes.SymmetricExceptWith(remove); } } #endif foreach (PolyMesh m in modifiedMeshes) { m.UpdateMeshFromData(); } base.UndoRedoPerformed(modified); }
protected override IResult CheckCell(IMapCell cell) { Queue <IMapCell> q = new Queue <IMapCell>(); ICollection <IMapCell> visitedCells = new HashSet <IMapCell>(); bool pacificConnected = false; bool atlanticConnectected = false; int startTime = System.Environment.TickCount; bool success = false; IMapCell startCell = cell; q.Enqueue(cell); while (q.Count > 0) { visitedCells.Add(cell); IEnumerable <IMapCell> possibleNeighbours = GetPossibleNeighbours(cell, visitedCells); possibleNeighbours.ToList().ForEach(pn => q.Enqueue(pn)); if (possibleNeighbours.Contains(_map.GetCell(0, 0))) { pacificConnected = true; } if (possibleNeighbours.Contains(_map.GetCell(_map.SizeY - 1, _map.SizeX - 1))) { atlanticConnectected = true; } if (pacificConnected && atlanticConnectected) { success = true; break; } cell = q.Dequeue(); } return(new Result(startCell, visitedCells.Count(), success)); }
static void Main(string[] args) { string samplesFileName = args[0]; string programFileName = args[1]; IEnumerable <(int[] startRegisters, int[] input, int[] expectedRegister)> inputs = SamplesParser.GetInput(samplesFileName); var operandNumberToNamesSetDictionary = new Dictionary <int, HashSet <string> >(); Processor proc = new Processor(); int part1Result = 0; foreach ((int[] startRegisters, int[] input, int[] expectedRegister) in inputs) { HashSet <string> matchingOperands = GetMatchingOperands(proc, startRegisters, input, expectedRegister).ToHashSet(); part1Result += matchingOperands.Count() >= 3 ? 1 : 0; int operand = input[0]; if (operandNumberToNamesSetDictionary.ContainsKey(operand)) { operandNumberToNamesSetDictionary[operand].IntersectWith(matchingOperands); } else { operandNumberToNamesSetDictionary[operand] = matchingOperands; } } Console.WriteLine(part1Result); // PART 2 var operandToInstructionNameMap = CalculateOperandNames(operandNumberToNamesSetDictionary); Processor proc2 = new Processor(); foreach (int[] instruction in ProgramParser.GetInput(programFileName)) { int operand = instruction[0]; proc2.Execute(operandToInstructionNameMap[operand], instruction[1], instruction[2], instruction[3]); } Console.WriteLine(proc2.Registers[0]); }
public static IEnumerable <IntVec2> Fill(IntVec2 s, IntVec2 t, SaveMap saveMap) { var ret = new HashSet <IntVec2>(); var cells = new Queue <IntVec2>(); cells.Enqueue(t); while (cells.Count() > 0 && ret.Count() < 15000) { var cell = cells.Dequeue(); if (cell.x < 0 || cell.y < 0 || cell.x >= saveMap.Width || cell.y >= saveMap.Height) { continue; } if (ret.Contains(cell)) { continue; } var addFlag = false; var neighborsFlag = false; if (addFlag) { ret.Add(cell); } if (neighborsFlag) { cells.Enqueue(cell + IntVec2.North); cells.Enqueue(cell + IntVec2.East); cells.Enqueue(cell + IntVec2.South); cells.Enqueue(cell + IntVec2.West); } } return(ret); }
public int Solution1(string input) { var activeCubes = new HashSet <Voxel>(); var lines = Parser.ToArrayOfString(input); for (var i = 0; i < lines.Length; i++) { var line = lines[i]; for (var j = 0; j < line.Length; j++) { if (line[j] == '#') { activeCubes.Add(new Voxel(j, i, 0)); } } } for (var i = 0; i < 6; i++) { var toTest = activeCubes.SelectMany(it => it.GetSurrounding()).Distinct().ToArray(); var newActive = new HashSet <Voxel>(); foreach (var item in toTest) { var isActive = activeCubes.Contains(item); var surrounding = item.GetSurrounding().Where(it => activeCubes.Contains(it)).Count(); if ((isActive && (surrounding == 2 || surrounding == 3)) || (!isActive && surrounding == 3)) { newActive.Add(item); } } activeCubes = newActive; } return(activeCubes.Count()); }
public bool IsBipartite(IList <IList <int> > graph) { int[] color = new int[graph.Count()]; Queue <int> q = new Queue <int>(); HashSet <int> hs = new HashSet <int>(); for (int i = 1; i < graph.Count(); i++) { hs.Add(i); } q.Enqueue(0); color[0] = 1; while (q.Count() != 0) { int n = q.Dequeue(); foreach (int i in graph[n]) { if (color[i] == 0) { q.Enqueue(i); color[i] = 3 - color[n]; hs.Remove(i); } else if (color[i] == color[n]) { return(false); } } if (q.Count() == 0 && hs.Count() != 0) { int tmp = hs.First(); color[tmp] = 1; q.Enqueue(tmp); hs.Remove(tmp); } } return(true); }
public List<SearchResult> Search(string query) { var results = new List<SearchResult>(); if (string.IsNullOrEmpty(query)) { return results; } var titlesReturned = new HashSet<string>(); var descriptionsReturned = new HashSet<string>(); int resultsTried = 0; while (titlesReturned.Count() < 10 && resultsTried < 300) { resultsTried++; var randomTitle = string.Join(" ", GetSentence(titleChain, 12)); var randomDescription = string.Join(" ", Enumerable.Range(0, rng.Next(1, 4)).SelectMany(_ => GetSentence(descriptionChain, 25))); if ((randomTitle.Contains(query.ToLower()) || randomDescription.Contains(query.ToLower())) && !titlesReturned.Contains(randomTitle) && !descriptionsReturned.Contains(randomDescription)) { titlesReturned.Add(randomTitle); descriptionsReturned.Add(randomDescription); results.Add(new SearchResult() { Title = TitleCase(randomTitle), Description = SentenceCase(randomDescription), Relevance = rng.Next(1, 6), Url = "#" }); } } return results; }
// Thanks @thefifthmatt :forestcat: public void CalculateIntervals() { Intervals = new Dictionary <Node, HashSet <Node> >(); var headers = new HashSet <Node> { BeginNode }; while (headers.Count() > 0) { var h = headers.First(); headers.Remove(h); var interval = new HashSet <Node> { h }; Intervals.Add(h, interval); h.Interval = interval; int lastCount = 0; while (lastCount != interval.Count) { lastCount = interval.Count; foreach (var start in interval.ToList()) { foreach (var cand in start.Successors) { if (cand.Predecessors.All(n => interval.Contains(n)) && !Intervals.ContainsKey(cand)) { interval.Add(cand); cand.Interval = interval; } } } } foreach (var cand in interval) { headers.UnionWith(cand.Successors.Except(interval).Except(Intervals.Keys)); } } }
public void SolvePartTwo() { santaX = 0; santaY = 0; coordinateSet = new HashSet <Coordinate>(); //starting point coordinateSet.Add(new Coordinate(santaX, santaY)); //for loop here foreach (var direction in _input[0]) { ExecutePartTwo(direction); Coordinate currentCoordinate; if (santasTurn) { currentCoordinate = new Coordinate(santaX, santaY); //this is new coordinate } else { currentCoordinate = new Coordinate(roboSantaX, roboSantaY); //this is new coordinate } //check if coordinate exists in set if (!coordinateSet.Contains(currentCoordinate)) { coordinateSet.Add(currentCoordinate); } //toggles boolean value santasTurn = !santasTurn; } //end loop and check count Console.WriteLine($"The solution to Day Three Part Two is {coordinateSet.Count()}"); }
private void RequestTasks() { if (sessions.Count() == 0) { return; } SendPingMessage(); while (failedSyncTasks.Count() > 0) { var failedTask = failedSyncTasks.First(); if (failedTask <= Blockchain.Singleton.Height) { failedSyncTasks.Remove(failedTask); continue; } if (!AssignSyncTask(failedTask)) { return; } } int taskCounts = sessions.Values.Sum(p => p.IndexTasks.Count); var highestBlockIndex = sessions.Values.Max(p => p.LastBlockIndex); for (; taskCounts < MaxSyncTasksCount; taskCounts++) { if (lastTaskIndex >= highestBlockIndex) { break; } if (!AssignSyncTask(++lastTaskIndex)) { break; } } }
public Dwarf(dfproto.BasicUnitInfo unit) { m_unit = unit; m_labors = new HashSet<DwarfLabor>(unit.LaborsList.Select(id => GameData.GetLabor(id))); m_skills = unit.SkillsList.ToDictionary(s => GameData.GetSkill(s.Id)); m_profession = new Lazy<DwarfProfession>(() => GameData.GetProfession(m_unit.Profession)); m_unskilled_count = m_labors.Count(l => !l.HasSkill); // look for the migrant counter to identify new migrants var migrant_counter_trait = unit.MiscTraitsList.FirstOrDefault(t => t.Id == MISC_TRAIT_MIGRANT_COUNTER); if (migrant_counter_trait != null) m_migrant_counter = migrant_counter_trait.Value; m_labors_view = m_labors.Where(l => l.HasSkill).Select(l => new DwarfListItem( l.Skill.Profession.Image, this, l)).ToList(); m_labors_potential_view = m_skills.Where(p => p.Key.HasLabor && !m_labors.Contains(p.Key.Labor)).Select(p => new DwarfListItem( p.Key.Profession.Image, this, p.Key.Labor)).ToList(); }