/// <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); } }
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; }
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 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); }
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 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; }
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); }
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 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 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 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 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; }
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); }
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 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); }
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 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 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))); }
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; }
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; }
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(); }