Пример #1
0
        public static Matrix Generate(Node parentNode)
        {
            Dictionary<Node, int> offsets = new Dictionary<Node, int>();

            int depth = parentNode.GetMaxDepth();
            int height = depth * (Settings.DefaultHeight + Settings.RoomCoridorLenght);

            var allNodes = new[] { parentNode }.FancyFlatten(n => true, n => n.Nodes).ToArray();

            var biggestLevel = allNodes.GroupBy(n => n.Level).OrderBy(g => g.Sum(n => n.GetSize())).Last();

            Console.WriteLine("Biggest level id " + biggestLevel.Key);
            Console.WriteLine("Biggest level count " + biggestLevel.Sum(n => n.GetSize()));

            int labyrinthWidth = parentNode.GetSize();

            Matrix matrix = new Matrix(labyrinthWidth, height);

            int yOffset = 0;
            int xOffset = 0;

            foreach (var levelGroup in allNodes.GroupBy(n => n.Level))
            {
                Node currentParent = null;

                foreach (Node groupNode in levelGroup)
                {
                    if (groupNode.Parent != null)
                    {
                        if (currentParent != groupNode.Parent)
                        {
                            yOffset = 0;
                        }
                    }

                    currentParent = groupNode.Parent;

                    Room room = new Room(groupNode.GetSize(), groupNode.Name, groupNode.Color, groupNode.Devices);

                    var parentOffset = 0;

                    if (groupNode.Parent != null)
                        parentOffset = offsets[groupNode.Parent];

                    matrix.Merge(room.AsMatrix(), yOffset + parentOffset, xOffset);

                    offsets.Add(groupNode, yOffset + parentOffset);

                    yOffset += groupNode.GetSize() + Settings.Scale;
                }

                xOffset += Settings.DefaultHeight + Settings.RoomCoridorLenght - 1;
                yOffset = 0;
            }

            return matrix;
        }
        public void GroupBy1()
        {
            var pairs = new[] 
            {
                KeyValuePair.Create("A", 1),
                KeyValuePair.Create("B", 2),
                KeyValuePair.Create("C", 3),
                KeyValuePair.Create("a", 4),
                KeyValuePair.Create("B", 5),
                KeyValuePair.Create("A", 6),
                KeyValuePair.Create("d", 7),
            };

            var groups = pairs.GroupBy(StringComparer.OrdinalIgnoreCase);
            AssertEx.SetEqual(new[] { "A", "B", "C", "d" }, groups.Keys);

            Assert.Equal(0, groups["A"].Key);
            AssertEx.Equal(new[] { 1, 4, 6 }, groups["A"].Value);

            Assert.Equal(0, groups["B"].Key);
            AssertEx.Equal(new[] { 2, 5 }, groups["B"].Value);

            Assert.Equal(3, groups["C"].Key);
            Assert.True(groups["C"].Value.IsDefault);

            Assert.Equal(7, groups["d"].Key);
            Assert.True(groups["d"].Value.IsDefault);
        }
Пример #3
0
        /// <summary>
        /// Compiles AST clauses into an executable program understood by the <see cref="Runtime.Engine"/> .
        /// The input clauses are not required to be in any particular order.
        /// </summary>
        public static Compiled.Program Compile (AST.Program program)
        {
            var allClauses = new []
                                 {
                                     program.DcgClauses.Select (DcgClauseToNormalClause),
                                     program.Clauses
                                 }.SelectMany (a => a);

            var clauseGroups = allClauses.GroupBy (c => Tuple.Create (c.Head.PredicateName, c.Head.Arguments.Length), c => c).ToArray ();

            var prologPredicates = clauseGroups.ToDictionary (p => p.Key, p => new Compiled.PrologPredicate {Name = p.Key.Item1});

            // Dictionary is not covariant so it takes a new dictionary to get a dictionary of base types (Predicate).
            var predicates = prologPredicates.ToDictionary (p => p.Key, CastPrologPredicateToBasePredicate); 

            if (program.ExternalPredicates != null)
            {
                foreach (var externalPredicate in program.ExternalPredicates)
                {
                    predicates.Add (Tuple.Create(externalPredicate.Name, externalPredicate.Arity), new Compiled.ExternalPredicate (externalPredicate.Name));
                }
            }

            foreach (var clauseGroup in clauseGroups)
            {
                var prologPredicate = prologPredicates [clauseGroup.Key];

                prologPredicate.Clauses = clauseGroup.Select (c => new Compiled.Clause {Head = new Compiled.Goal {Predicate = prologPredicate, Arguments = c.Head.Arguments},
                                                                                      Body = Compile (c.Body, predicates)}).ToArray ();
            }

            return new Compiled.Program (predicates);
        }
        public static void Main()
        {
            var students = new[]
            {
                new { FirstName = "Eminem", Group = "Mathematics" },
                new { FirstName = "DMX", Group = "Geography" },
                new { FirstName = "2Pac", Group = "History" },
                new { FirstName = "Spens", Group = "Mathematics" },
                new { FirstName = "Rick Ross", Group = "History" },
                new { FirstName = "Mary J Blige", Group = "History" },
                new { FirstName = "Lil Jon", Group = "Mathematics" },
                new { FirstName = "Gucci Mane", Group = "Geography" },
                new { FirstName = "Hazarta", Group = "Mathematics" },
            };

            // 18.LINQ
            // var groupedStudents =
            //     from st in students
            //     group st by st.Group into g
            //     orderby g.Key
            //     select g;

            // 19.Lambda expression
            var groupedStudents = students.GroupBy(st => st.Group).OrderBy(g => g.Key);

            foreach (var group in groupedStudents)
            {
                foreach (var student in group)
                {
                    Console.WriteLine("{0,11} - {1}", student.Group, student.FirstName);
                }
            }
        }
Пример #5
0
 public void NeedToSubscribeImediatelyWhenSplitting()
 {
     var averages = new[] {0.0, 0.0};
     var numbers = new[] {22, 22, 99, 22, 101, 22}.ToObservable();
     var split = numbers.GroupBy(n => n%2);
     split.Subscribe((IGroupedObservable<int, int> g) => g.Average().Subscribe(a => averages[g.Key] = a));
     Assert.AreEqual(22, averages[0]);
     Assert.AreEqual(100, averages[1]);
 }
Пример #6
0
        public void TestMethod()
        {
            var doclist = new[] {
                new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent3", "Ent4", "Ent5" } },
                new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent1", "Ent6", "Ent7" } },
                new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent8", "Ent9" } },
                new {RelatingDocument = "Doc2", RelatedObjects = new List<string>() { "Ent1", "Ent6", "Ent7" } },
                new {RelatingDocument = "Doc3", RelatedObjects = new List<string>() { "Ent1", "Ent6" } },
                new {RelatingDocument = "Doc4", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent7" } },
                new {RelatingDocument = "Doc5", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent3" } },
                new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent10", "Ent11" } },
                new {RelatingDocument = "Doc2", RelatedObjects = new List<string>() { "Ent10", "Ent11" } },
            }.ToList();

            Dictionary<string, List<string>> dic = null;
            //check for duplicates
            var dups = doclist.GroupBy(d => d.RelatingDocument).SelectMany(grp => grp.Skip(1));
            //combine object lists to single key value, merge lists
            var dupsMerge = dups.GroupBy(d => d.RelatingDocument).Select(p => new { x = p.Key, y = p.SelectMany(c => c.RelatedObjects) });

            if (dupsMerge.Any())
            {
                //remove the duplicates and convert to dictionary
                dic = doclist.Except(dups).ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects);

                //add the duplicate doc referenced object lists to the original doc
                foreach (var item in dupsMerge)
                {
                    dic[item.x] = dic[item.x].Union(item.y).ToList();
                }
            }
            else
            {
                //no duplicates, so just convert to dictionary
                dic = doclist.ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects);
            }

            //reverse lookup to entity to list of documents
            var newDic = dic
                            .SelectMany(pair => pair.Value
                            .Select(val => new { Key = val, Value = pair.Key }))
                            .GroupBy(item => item.Key)
                            .ToDictionary(gr => gr.Key, gr => gr.Select(item => item.Value));

            Assert.AreEqual(newDic["Ent1"].Count(), 5);
            Assert.AreEqual(newDic["Ent2"].Count(), 3);
            Assert.AreEqual(newDic["Ent3"].Count(), 2);
            Assert.AreEqual(newDic["Ent4"].Count(), 1);
            Assert.AreEqual(newDic["Ent5"].Count(), 1);
            Assert.AreEqual(newDic["Ent6"].Count(), 3);
            Assert.AreEqual(newDic["Ent7"].Count(), 3);
            Assert.AreEqual(newDic["Ent8"].Count(), 1);
            Assert.AreEqual(newDic["Ent9"].Count(), 1);
            Assert.AreEqual(newDic["Ent10"].Count(), 2);
            Assert.AreEqual(newDic["Ent11"].Count(), 2);
        }
        static void Main()
        {
            var numbers = new[] { 3, 4, 4, 2, 3, 3, 4, 3, 2 };

            var groupedByOccurence = numbers.GroupBy(x => x).OrderBy(x => x.Key);

            foreach (var group in groupedByOccurence)
            {
                Console.WriteLine("{0} --> {1} times", group.Key, group.Count());
            }
        }
Пример #8
0
        public static Matrix Generate(Node parentNode)
        {
            Dictionary<Node, int> offsets = new Dictionary<Node, int>();

            int depth = parentNode.GetMaxDepth();

            int height = depth * (Settings.DefaultHeight + Settings.RoomCoridorLenght);

            var allNodes = new []{parentNode}.FancyFlatten(n => true, n => n.Nodes).ToArray();

            int labyrinthWidth = parentNode.GetSize();

            Matrix matrix = new Matrix(labyrinthWidth, height);

            int yOffset = 0;
            int xOffset = 0;

            foreach (var levelGroup in allNodes.GroupBy(n => n.Level))
            {
                Node currentParent = null;

                foreach (var group in levelGroup)
                {
                    if (group.Parent != null)
                    {
                        if (currentParent != group.Parent)
                        {
                            yOffset = 0;
                        }
                    }

                    currentParent = group.Parent;

                    Room room = new Room(group.GetSize());

                    var parentOffset = 0;

                    if (group.Parent != null)
                        parentOffset = offsets[group.Parent];

                    matrix.Merge(room.AsMatrix(), yOffset + parentOffset, xOffset);

                    offsets.Add(group, yOffset + parentOffset);

                    yOffset += group.GetSize() + Settings.Scale;
                }

                xOffset += Settings.DefaultHeight + Settings.RoomCoridorLenght - 1;
                yOffset = 0;
            }

            return matrix;
        }
        public static void Main()
        {
            var array = new[] { "C#", "SQL", "PHP", "PHP", "SQL", "SQL" };

            var dictionary = array.GroupBy(s => s).ToDictionary(s => s.Key, s => s.Count());

            var listofEvens = dictionary.Where(s => s.Value%2 == 0).Select(s => s.Key).ToList();
            var listofOdds = dictionary.Where(s => s.Value%2 != 0).Select(s => s.Key).ToList();

            Console.WriteLine(string.Format("Language/s with even number of appearance {0}", string.Join(", ", listofEvens)));
            Console.WriteLine(string.Format("Language/s with odd number of appearance {0}", string.Join(", ", listofOdds)));
        }
Пример #10
0
 private static void f2()
 {
     //z2
     //сгруппировать по чётности, для каждой группы посчитать сумму
     //итоговая коллекция должна содержать поле суммы и группу
     int[] a = new[] {3, 2, 8, 4, 2, 5, 3, 9, 1, 4, 2, 6, 7, 4, 7};
     var n = a.GroupBy(x_ => x_%2 == 0).Select(ints => new {s = ints.Sum(), col = ints.ToArray()});
     foreach (var el in n)
     {
         Console.WriteLine(el.s);
         el.col.ToList().ForEach(x_ => Console.Write("{0} ", x_));
         Console.WriteLine();
     }
 }
Пример #11
0
        public static void Main()
        {
            var numbers = new[] { 3, 4, 4, 2, 3, 3, 4, 3, 2 };

            var groupedNumbers = numbers.GroupBy(n => n).OrderBy(n => n.Key);

            Console.WriteLine("List: [{0}]", string.Join(", ", numbers));
            Console.WriteLine(new string('-', 30));

            foreach (var numberGroup in groupedNumbers)
            {
                Console.WriteLine("{0} occurs {1} times", numberGroup.Key, numberGroup.Count());
            }
        }
Пример #12
0
        static void Main()
        {
            // sample data with no majorant, uncomment this and comment the other sample if you want to test it
            // var numbers = new[] { 3, 4, 4, 2, 3, 3, 4, 3, 2 };

            // sample data with majorant
            var numbers = new[] { 2, 2, 3, 3, 2, 3, 4, 3, 3 };

            Console.WriteLine(string.Join(", ", numbers));
            var groupedByOccurence = numbers.GroupBy(x => x).OrderByDescending(x => x.Count()).FirstOrDefault();

            if (groupedByOccurence != null && groupedByOccurence.Count()> numbers.Count() / 2)
            {
                Console.WriteLine("Majorant --> {0} ({1} occurences)", groupedByOccurence.Key, groupedByOccurence.Count());
                return;
            }

            Console.WriteLine("No majorant in the given sequence.");
        }
Пример #13
0
        public void Quesion3()
        {
            var data = new[] {
                 new Car{ Model="A", Colour="Blue"},
                 new Car{ Model="B", Colour="Blue"},
                 new Car{ Model="A", Colour="Red"},
                 new Car{ Model="C", Colour="Green"},
                 new Car{ Model="D", Colour="Blue"},
                 new Car{ Model="C", Colour="Red"},
            };

            var qry = data.GroupBy(c => c.Colour)
                          .Where(g => g.Count() > 1);
 
            foreach (var result in qry)
            {
                 Console.WriteLine("{0}-{1}", result.Key, result.Count());
            }            
        }
Пример #14
0
 private static void f3()
 {
     //z3
     //дана коллекция пар - фамилия и сумма
     //необходимо составить итоговую коллекцию - фамилия и сумма всех сумм для данной фамилии
     KeyValuePair<string, int>[] kvp = new[]
     {
         new KeyValuePair<string, int>("Иванов", 2),
         new KeyValuePair<string, int>("Петров", 3),
         new KeyValuePair<string, int>("Иванов", 10),
         new KeyValuePair<string, int>("Петров", 6),
         new KeyValuePair<string, int>("Федоров", 1),
     };
     KeyValuePair<String, int> k = new KeyValuePair<string, int>("aa", 3);
     var n3 = kvp.GroupBy(x_ => x_.Key).Select(pairs => new {name = pairs.Key, sum = pairs.Sum(pair => pair.Value)});
     foreach (var el in n3)
     {
         Console.WriteLine(el);
     }
 }
Пример #15
0
        static void Main(string[] args)
        {
            var books = new[]
            {
                new Book() {Name = "11", Year = 2010},
                new Book() {Name = "12", Year = 2011}
            };

            IEnumerable<IGrouping<int, Book>> groups = 
                books.GroupBy(b => b.Year);

            IEnumerable<IGrouping<int, Book>> yearGroups = 
                from book in books
                from book2 in books
                let year= book.Year-book2.Year
                group book by book.Year
                into g 
                select g;

            var bookGroups = 
                from g in yearGroups
                orderby g.Key descending
                select new {Year = g.Key, Books = g, Count=g.Count()};
        }
Пример #16
0
 public void Should_return_an_empty_group_for_each_instance_of_the_separator()
 {
     var lines = new[] { "a", "a", "a" };
     var grouped = lines.GroupBy("a");
     grouped.Count.ShouldBeEqualTo(lines.Length);
     grouped.First().Count.ShouldBeEqualTo(0);
     grouped.Skip(1).First().Count.ShouldBeEqualTo(0);
     grouped.Skip(2).First().Count.ShouldBeEqualTo(0);
 }
Пример #17
0
        public void SimpleGroupBy()
        {
            var source = new[] { "one", "two", "three", "four" };
            var result = source.GroupBy(x => x.Count());

            Assert.AreEqual(3, result.Count());
            result.First(g=>g.Key == 3).AssertSequenceEqual("one","two");
            result.First(g => g.Key == 4).AssertSequenceEqual("four");
            result.First(g => g.Key == 5).AssertSequenceEqual("three");
        }
Пример #18
0
        public void GroupBy()
        {
            var items = new[]
            {
                new KeyValueClass { Key = "a", Value = 2 },
                new KeyValueClass { Key = "a", Value = 1 },
                new KeyValueClass { Key = "b", Value = 1 },
                new KeyValueClass { Key = "c", Value = 3 },
                new KeyValueClass { Key = "c", Value = 4 },
                new KeyValueClass { Key = "c", Value = 1 },
            };

            var groups = items.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToArray());
            var a = groups["a"];
            var b = groups["b"];
            var c = groups["c"];
            AssertEquals(a[0], 2);
            AssertEquals(a[1], 1);
            AssertEquals(b[0], 1);
            AssertEquals(c[0], 3);
            AssertEquals(c[1], 4);
            AssertEquals(c[2], 1);
        }
Пример #19
0
        private void GroupingTest()
        {
            IEnumerable<Business> companies = new[]{
                new Business{ Name = "XYZ Inc.", Settings = new[]{ 
                    new Setting{ Name="Age", Value="27"},
                    new Setting{ Name="Industry", Value="IT"}
                }},
                new Business{ Name = "Programmers++", Settings = new[]{ 
                    new Setting{ Name="Age", Value="27"},
                    new Setting{ Name="Industry", Value="IT"}
                }},
                new Business{ Name = "Jeff's Luxury Salmon", Settings = new[]{ 
                    new Setting{ Name="Age", Value="63"},
                    new Setting{ Name="Industry", Value="Sports"}
                }},
                new Business{ Name = "Bank of Khazakstan", Settings = new[]{ 
                    new Setting{ Name="Age", Value="30"},
                    new Setting{ Name="Industry", Value="Finance"}
                }},
            };

            var groupSetting = "Industry";

            var grouped = companies
                .GroupBy(c => c.Settings.First(s => s.Name == groupSetting).Value);


            foreach (var group in grouped)
            {
                //Console.WriteLine(group.Key);
                foreach (var item in group.OrderBy(bus => bus.Name))
                    Console.WriteLine(" - " + item.Name);
            }
        }
Пример #20
0
        private static void AddTypeToNamespaceNode(PropertyBag node, Type type)
        {
            object value;
            var name = type.GetRootName();
            if (!node.TryGetValue(name, out value))
            {
                node.SetPropertyNoCheck(name, HostType.Wrap(type));
                return;
            }

            var hostType = value as HostType;
            if (hostType != null)
            {
                var types = new[] { type }.Concat(hostType.Types).ToArray();

                var groups = types.GroupBy(testType => testType.GetGenericParamCount()).ToIList();
                if (groups.Any(group => group.Count() > 1))
                {
                    types = groups.Select(ResolveTypeConflict).ToArray();
                }

                node.SetPropertyNoCheck(name, HostType.Wrap(types));
                return;
            }

            if (value is PropertyBag)
            {
                throw new OperationCanceledException(MiscHelpers.FormatInvariant("Type conflicts with namespace at '{0}'", type.GetLocator()));
            }

            throw new OperationCanceledException(MiscHelpers.FormatInvariant("Type conflicts with '{0}' at '{1}'", value.GetFriendlyName(), type.GetLocator()));
        }
Пример #21
0
 public void Should_remove_the_whitespace_lines()
 {
     var lines = new[] { " ", "\t", "a", "\r", "\n" };
     var grouped = lines.GroupBy("d");
     grouped.Count.ShouldBeEqualTo(1);
     grouped.First().Count.ShouldBeEqualTo(1);
     grouped.First().ShouldContainAllInOrder(new[] { "a" });
 }
Пример #22
0
 public void Should_return_the_entire_input_in_a_single_group()
 {
     var lines = new[] { "a", "b", "c" };
     var grouped = lines.GroupBy("d");
     grouped.Count.ShouldBeEqualTo(1);
     grouped.First().ShouldContainAllInOrder(lines);
 }
Пример #23
0
 public void Should_return_an_empty_group()
 {
     var lines = new[] { "a" };
     var grouped = lines.GroupBy("a");
     grouped.Count.ShouldBeEqualTo(lines.Length);
     grouped.First().Count.ShouldBeEqualTo(0);
 }
Пример #24
0
 public void Should_return_the_data_in_one_group()
 {
     var lines = new[] { "a", "b", "c", "d", "e" };
     var grouped = lines.GroupBy("c");
     grouped.Count.ShouldBeEqualTo(2);
     grouped.First().ShouldContainAllInOrder(new[] { "a", "b" });
     grouped.Last().ShouldContainAllInOrder(new[] { "d", "e" });
 }