public IPuzzleOutput Solve() { var inputLines = File.ReadAllLines(inputFile); var locToInt = new Dictionary <(int, int), SquareVal>(); var claimIdToSize = new Dictionary <int, int>(); foreach (var line in inputLines) { var lineSplit = line.Split(" "); var marginStr = lineSplit[2].TrimEnd(':').Split(","); var sizingStr = lineSplit[3].Split("x"); var margins = marginStr.Select(int.Parse).ToArray(); var sizing = sizingStr.Select(int.Parse).ToArray(); var claimId = int.Parse(lineSplit[0].TrimStart('#')); claimIdToSize.Add(claimId, sizing[0] * sizing[1]); for (int y = margins[1]; y < margins[1] + sizing[1]; ++y) { for (int x = margins[0]; x < margins[0] + sizing[0]; ++x) { (int, int)loc = (x, y); if (locToInt.ContainsKey(loc)) { locToInt[loc].AddClaim(claimId); } else { locToInt.Add(loc, new SquareVal(claimId)); } } } } var overlaps = locToInt.Count((a) => a.Value.NumClaims > 1); var nonOverlappingSquares = locToInt.Where(x => x.Value.NumClaims == 1); var remainingClaims = nonOverlappingSquares.SelectMany(x => x.Value.Claims).Distinct(); var claimToActualSize = new Dictionary <int, int>(); foreach (var square in nonOverlappingSquares) { var claimId = square.Value.Claims[0]; if (!claimToActualSize.ContainsKey(claimId)) { claimToActualSize.Add(claimId, 1); } else { claimToActualSize[claimId] = claimToActualSize[claimId] + 1; } } var claimIdWithoutOverlap = claimIdToSize.Intersect(claimToActualSize).First().Key; return(new TwoPartPuzzleOutput(new Day3Part1SolverOutput(overlaps), new Day3Part2SolverOutput(claimIdWithoutOverlap))); }
public void TestDictionaryExtensions() { { var a = new Dictionary <string, string>() { { "key1", "a" }, { "key2", "b" } }; var b = new Dictionary <string, string>() { { "key1", "a" } }; Assert.Equal("[key1, a]", a.Intersect(b).Single().ToString()); Assert.Equal("[key2, b]", a.ExceptKeys(b).Single().ToString()); } { var a = new HashSet <string>() { "a", "b" }; var b = new HashSet <string>() { "c", "d" }; Assert.True(a.AddRange(b)); Assert.Equal("[a, b, c, d]", a.ToStringV2(x => "" + x)); Assert.False(a.AddRange(b)); Assert.Equal("[a, b, c, d]", a.ToStringV2(x => "" + x)); } }
public IEnumerable <FileSnapshot> GetChangedSnapshots(string[] filters = null) { return(_currentSnapshot .Intersect(_previousSnapshot, _comparer) .Where(x => MatchPattern(x.Key, filters)) .Where(x => !x.Value.Equals(_previousSnapshot[x.Key])) .Select(x => x.Value)); }
public void IntersectNoEqualityComparer_SameKeyInSecondDict_TakesDuplicateKeyValuePair() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, {6, 4} }; var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } }; var expected = 1; var actual = first.Intersect(second).Count; Assert.AreEqual(expected, actual); }
public void IntersectDefaultEqualityComparer_SameKeyDifferentValues_OnlyKeepsMatchingKeyAndValue() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, {6, 4} }; var second = new SortedList<int, int> { { 3, 2 }, { 6, 4 } }; var expected = 1; var actual = first.Intersect(second, EqualityComparer<KeyValuePair<int, int>>.Default).Count; Assert.AreEqual(expected, actual); }
private static Dictionary <int, char> CompareDictionaries(Dictionary <int, char> curLine, Dictionary <int, char> compLine) { compCount++; if (compCount % 100 == 0) { Console.WriteLine("CompareCount: {0}", compCount); } Dictionary <int, char> same = curLine.Intersect(compLine).ToDictionary(x => x.Key, x => x.Value); if (same.Count == curLine.Count - 1) { return(same); } return(null); }
private void CheckData(int size) { var result = new Dictionary <TKey, TValue>(); using (var nativeHashMapEnumerator = _nativeHashMap.GetEnumerator()) { while (nativeHashMapEnumerator.MoveNext()) { var data = nativeHashMapEnumerator.Current; Assert.IsFalse(result.ContainsKey(data.Key)); result.Add(data.Key, data.Value); } } Assert.AreEqual(size, result.Count); Assert.AreEqual(result.Intersect(_checkingResults).Count(), result.Union(_checkingResults).Count()); }
public Fixup(DataElement parent, Dictionary <string, Variant> args, params string[] refs) { this.parent = parent; this.args = args; if (!refs.SequenceEqual(refs.Intersect(args.Keys))) { string msg = string.Format("Error, {0} requires a '{1}' argument!", this.GetType().Name, string.Join("' AND '", refs)); throw new PeachException(msg); } foreach (var item in refs) { this.refs.Add(item, (string)args[item]); } }
private void PopulateSheets() { foreach (Excel.Worksheet ws in _excelDiffViewModel.XlLeftWorkBook.Worksheets) { _leftWorkBookSheets.Add(ws.Name, ws.UsedRange.Count); } foreach (Excel.Worksheet ws in _excelDiffViewModel.XlRightWorkBook.Worksheets) { _rightWorkBookSheets.Add(ws.Name, ws.UsedRange.Count); } // find sheets that are present in both dictionaries _commonInBothSheets = _rightWorkBookSheets.Intersect(_leftWorkBookSheets).ToDictionary(x => x.Key, x => x.Value); // find sheets that are present only in Left but not in Right _onlyInLeftSheets = _leftWorkBookSheets.Except(_rightWorkBookSheets).ToDictionary(x => x.Key, x => x.Value); // find sheets that are present only in Right but not in Left _onlyInRightSheets = _rightWorkBookSheets.Except(_leftWorkBookSheets).ToDictionary(x => x.Key, x => x.Value); }
public void TestListCompare() { var firstDictionary = new Dictionary<string, string> { { "a", "1" }, { "c", "3" }, { "b", "2" } }; var secondDictionary = new Dictionary<string, string> { { "c", "3" }, { "a", "1" }, { "b", "2" } }; var thirdDictionary = new Dictionary<string, string> { { "a", "5" }, { "c", "3" }, { "b", "2" } }; var fourthDictionray = new Dictionary<string, string> { { "a", "1" }, { "c", "3" }, { "b", "2" }, { "d", "4" } }; Console.WriteLine($"Object.Equals: {firstDictionary.Equals(secondDictionary)}"); Console.WriteLine($"Enumerable.SequenceEqual: {firstDictionary.SequenceEqual(secondDictionary)}"); Console.WriteLine($"firstDictionary.Except: {!firstDictionary.Except(secondDictionary).Any()}"); Console.WriteLine($"secondDictionary.Except: {!secondDictionary.Except(firstDictionary).Any()}"); Console.WriteLine($"firstDictionary.Intersect.Except: {firstDictionary.Intersect(secondDictionary).Count() == secondDictionary.Count()}"); Console.WriteLine($"first compared to second: {EnumerablesAreEquivalent(firstDictionary, secondDictionary)}"); Console.WriteLine($"first compared to third: {EnumerablesAreEquivalent(firstDictionary, thirdDictionary)}"); Console.WriteLine($"first compared to fourth: {EnumerablesAreEquivalent(firstDictionary, fourthDictionray)}"); }
private void timer_elapsed(object sender, ElapsedEventArgs args) { files_realtime.Clear(); List <string> dir_files = new List <string> (System.IO.Directory.GetFiles(this.PathName, this.searchPattern)); dir_files.ForEach(f => { if (!files_realtime.ContainsKey(f)) { files_realtime.Add(f, new PyFileInfo(f, get_file_md5(f), Status.None)); } }); var both = files_realtime.Intersect(files_last, new PyFileInfoCompare()); var files_added_or_modified = files_realtime.Except(both, new PyFileInfoCompare()); var files_removed = files_last.Except(files_realtime, new PyFilenameCompare()); foreach (var item in files_added_or_modified) { item.Value.status = Status.Added_Modified; if (OnFileChanged != null) { OnFileChanged(this, new FileChangedEventArgs(item.Value)); item.Value.status = Status.None; } } foreach (var item in files_removed) { item.Value.status = Status.Removed; if (OnFileChanged != null) { OnFileChanged(this, new FileChangedEventArgs(item.Value)); item.Value.status = Status.None; } } files_last = files_realtime.ToDictionary(k => k.Key, v => v.Value); }
public static bool TraceEquivalent(this Dictionary <String, List <String> > A, Dictionary <String, List <String> > B) { KeyEqualityComparer <string, List <String> > comparer = new KeyEqualityComparer <string, List <string> >(); return(A.Intersect(B, comparer).Count() == A.Union(B, comparer).Count()); }
//Персечение вычисляется как морфизмы, одновременно содержащиеся и в l и в r private static Dictionary <string, Конус> ВычислитьПересечение(Dictionary <string, Конус> l, Dictionary <string, Конус> r) { Dictionary <string, Конус> результат = new Dictionary <string, Конус>(l); return(результат.Intersect(r).ToDictionary(m => m.Key, m => m.Value)); }
static void ranking(LifeExpectancyAnalyzer analyzer) { while (true) { string str_year_of_interest = prompt("Enter year of interest (-1 to quit): "); int year_of_interest; if (!int.TryParse(str_year_of_interest, out year_of_interest)) { l("Error parsing year of interest, integers only please!"); continue; } if (year_of_interest == -1) { break; } string user_input_region_name = prompt("Enter region (type 'all' to consider all): "); if (user_input_region_name != "all" && !analyzer.Regions.Contains(user_input_region_name)) { l("No such region!"); continue; } string user_input_income_category = prompt("Enter income category (type 'all' to consider all): "); if (user_input_income_category != "all" && !analyzer.Income_Groups.Contains(user_input_income_category)) { l("No such income category!"); continue; } Dictionary <string, Entity> countries_filtered_by_region = (user_input_region_name == "all" ? analyzer.Entities : analyzer.Entities_By_Region(user_input_region_name)); Dictionary <string, Entity> countries_filtered_by_income_category = (user_input_income_category == "all" ? countries_filtered_by_region : countries_filtered_by_region.Intersect( analyzer.Entities_By_Income_Group(user_input_income_category) ).ToDictionary(k => k.Key, k => countries_filtered_by_region[k.Key])); Dictionary <string, Entity> countries_filtered_by_has_data = countries_filtered_by_income_category.Where(p => p.Value.LifeExpectancyByYear.ContainsKey(year_of_interest)).ToDictionary(p => p.Key, p => p.Value); Dictionary <string, Entity> sorted_countries_dict = countries_filtered_by_has_data.OrderByDescending( p => p.Value.LifeExpectancyByYear[year_of_interest] ).ToDictionary(p => p.Key, p => p.Value); List <Entity> sorted_countries = sorted_countries_dict.Values.ToList(); l("Top 10 Life Expectancy for ", year_of_interest); for (int i = 0; i < (sorted_countries.Count >= 10 ? 10 : sorted_countries.Count); i++) { l(i + 1, ": ", sorted_countries[i].Country_Name, " ", sorted_countries[i].LifeExpectancyByYear[year_of_interest]); } l(); l("Bottom 10 Life Expectancy for ", year_of_interest); for (int i = sorted_countries.Count - 1; i > (sorted_countries.Count - 1) - (sorted_countries.Count >= 10 ? 10 : sorted_countries.Count); i--) { l(i + 1, ": ", sorted_countries[i].Country_Name, " ", sorted_countries[i].LifeExpectancyByYear[year_of_interest]); } } }
/// <summary> /// Removes the two objects at the top of the stack and adds them together. /// Then, pushes the result on to the top of the stack. /// </summary> public override void PerformOperation() { base.PerformOperation(); // If we have fewer than 2 objects on the stack we are el-bonerino-ed Debug.Assert(CelesteStack.StackSize >= 2, "Not enough elements on the stack for add operator"); CelesteObject rhs = CelesteStack.Pop(); CelesteObject lhs = CelesteStack.Pop(); // The stack will wrap our addition result in a CelesteObject, so just push the actual value of the addition if (lhs.IsNumber() && rhs.IsNumber()) { CelesteStack.Push(lhs.As <float>() + rhs.As <float>()); } else if (lhs.IsString() && rhs.IsString()) { CelesteStack.Push(lhs.As <string>() + rhs.As <string>()); } else if (lhs.IsList() && rhs.IsList()) { lhs.AsList <object>().AddRange(rhs.AsList <object>()); CelesteStack.Push(lhs); } else if (lhs.IsTable() && rhs.IsTable()) { Dictionary <object, object> lhsTable = lhs.AsTable(); Dictionary <object, object> rhsTable = rhs.AsTable(); // Tables can be added, but only if they are all indexed by number or string completely // No other way can be used because the reference type of 'object' makes value equality difficult // These two types of adding are the only two we can realistically support // Check whether our lhs table has all number keys if (lhsTable.Keys.Count(x => x is float) == lhsTable.Keys.Count) { // If it does, check the rhs table too if (rhsTable.Keys.Count(x => x is float) == rhsTable.Keys.Count) { // We now go through and see if any keys overlap in the two tables if (lhsTable.Intersect(rhsTable, new TableKeyComparer()).Count() == 0) { foreach (KeyValuePair <object, object> pair in rhsTable) { lhsTable.Add((float)pair.Key, pair.Value); } } else { Debug.Fail("Invalid parameters to add operation. Right hand side table has at least one key the same as the left hand side table"); } } else { Debug.Fail("Invalid parameters to add operation. Right hand side table has inconsistent key types (should be numbers)"); } } // Check whether our lhs table has all string keys else if (lhsTable.Keys.Count(x => x is string) == lhsTable.Keys.Count) { // If it does, check the rhs table too if (rhsTable.Keys.Count(x => x is string) == rhsTable.Keys.Count) { // We now go through and see if any keys overlap in the two tables if (lhsTable.Intersect(rhsTable, new TableKeyComparer()).Count() == 0) { foreach (KeyValuePair <object, object> pair in rhsTable) { lhsTable.Add((string)pair.Key, pair.Value); } } else { Debug.Fail("Invalid parameters to add operation. Right hand side table has at least one key the same as the left hand side table"); } } else { Debug.Fail("Invalid parameters to add operation. Right hand side table has inconsistent key types (should be strings)"); } } else { Debug.Fail("Invalid parameters to add operation. Left hand side table has inconsistent key types (should be numbers or strings)"); } CelesteStack.Push(lhs); } else { Debug.Fail("Invalid parameters to add operation."); } }
static void Main(string[] args) { //equ Vector3 a = new Vector3(0, 0, 0); Vector3 b = new Vector3(1, 0, 0); bool bE = a.Equals(b); //bE = a == b; //struct key Dictionary <Vector3, CustomClass> dic = new Dictionary <Vector3, CustomClass>(new Vector3Comparer()); Vector3 key1 = new Vector3(0, 0, 0); CustomClass value1 = new CustomClass(0, 0, 0); dic.Add(key1, value1); key1.x = 1; dic.Add(key1, value1); Dictionary <Vector3, CustomClass> dicCopy = new Dictionary <Vector3, CustomClass>(new Vector3Comparer()); key1.x = 0; dicCopy.Add(key1, value1); key1.x = 3; dicCopy.Add(key1, value1); Dictionary <Vector3, CustomClass> unionDic = new Dictionary <Vector3, CustomClass>(new Vector3Comparer()); var unionList = dicCopy.Union(dic); foreach (var pair in unionList) { var k1 = pair.Key; var v1 = pair.Value; unionDic.Add(k1, v1); } Dictionary <Vector3, CustomClass> interDic = new Dictionary <Vector3, CustomClass>(new Vector3Comparer()); var interList = dicCopy.Intersect(dic); foreach (var pair in interList) { var k1 = pair.Key; var v1 = pair.Value; interDic.Add(k1, v1); } bool aaa = false; bool bEqual = interDic == unionDic; //class key // Dictionary<KeyClass, CustomClass> dic2 = new Dictionary<KeyClass, CustomClass>(); // // KeyClass k = new KeyClass(0); // dic2.Add(k, value1); // // value1.x = 1; // k.x = 1; // dic2.Add(k, value1); }