コード例 #1
0
ファイル: Program.cs プロジェクト: dgrigorov/TelerikAcademy-1
    static long Calc(long n)
    {
        if (n == 1)
            return 0;

        var queue = new OrderedBag<State>((pair1, pair2) =>
            pair1.Value.CompareTo(pair2.Value)
        );

        queue.Add(new State(n, 0));

        while (queue.Count != 0)
        {
            var currentState = queue.RemoveFirst();

            if (currentState.Key == 1)
                return currentState.Value;

            for (int power = 2; power < 60; power++)
            {
                var powerBase = Math.Pow(currentState.Key, 1.0 / power);

                var nextNumber = (long)Math.Round(powerBase);
                var nextSteps = Math.Abs(Pow(nextNumber, power) - currentState.Key);

                var nextState = new State(nextNumber, currentState.Value + nextSteps + 1);
                queue.Add(nextState);
            }
        }

        throw new ArgumentException();
    }
コード例 #2
0
        private static ICollection<Path> GetNeighbourhood()
        {
            OrderedBag<Path> neighbourhood = new OrderedBag<Path>();

            neighbourhood.Add(new Path(new House("1"), new House("2"), 2));
            neighbourhood.Add(new Path(new House("1"), new House("3"), 22));
            neighbourhood.Add(new Path(new House("1"), new House("10"), 7));
            neighbourhood.Add(new Path(new House("2"), new House("10"), 12));
            neighbourhood.Add(new Path(new House("2"), new House("9"), 4));
            neighbourhood.Add(new Path(new House("2"), new House("3"), 1));
            neighbourhood.Add(new Path(new House("3"), new House("5"), 7));
            neighbourhood.Add(new Path(new House("4"), new House("3"), 9));
            neighbourhood.Add(new Path(new House("10"), new House("8"), 12));
            neighbourhood.Add(new Path(new House("8"), new House("6"), 17));
            neighbourhood.Add(new Path(new House("8"), new House("7"), 8));
            neighbourhood.Add(new Path(new House("5"), new House("7"), 9));
            neighbourhood.Add(new Path(new House("6"), new House("5"), 18));
            neighbourhood.Add(new Path(new House("4"), new House("5"), 7));
            neighbourhood.Add(new Path(new House("4"), new House("6"), 13));
            neighbourhood.Add(new Path(new House("4"), new House("9"), 4));
            neighbourhood.Add(new Path(new House("8"), new House("9"), 5));
            neighbourhood.Add(new Path(new House("4"), new House("8"), 6));

            return neighbourhood;
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: dgrigorov/TelerikAcademy-1
    private static IList<int> Dijkstra(int start)
    {
        var distances = Enumerable.Repeat(int.MaxValue, graph.Count).ToArray();

        var queue = new OrderedBag<Node>((node1, node2) =>
            node1.Distance.CompareTo(node2.Distance)
        );

        distances[start] = 0;
        queue.Add(new Node(start, 0));

        while (queue.Count != 0)
        {
            var currentNode = queue.RemoveFirst();

            foreach (var neighborNode in graph[currentNode.To])
            {
                int currentDistance = distances[currentNode.To] + neighborNode.Distance;

                if (currentDistance < distances[neighborNode.To])
                {
                    distances[neighborNode.To] = currentDistance;
                    queue.Add(new Node(neighborNode.To, currentDistance));
                }
            }

            // Removing repeating is actually slower?
        }

        return distances;
    }
コード例 #4
0
        public static void Main(string[] args)
        {
            for (int i = 0; i < 4; i++)
            {
                var start = new KeyValuePair<BigInteger, int>(1, 0);
                BigInteger desired = BigInteger.Parse(Console.ReadLine());
                var results = new OrderedBag<KeyValuePair<BigInteger, int>>((x, y) => x.Value.CompareTo(y.Value));
                results.Add(start);

                var current = start;

                HashSet<BigInteger> used = new HashSet<BigInteger>();
                while (current.Key != desired)
                {
                    current = results.RemoveFirst();
                    if (!used.Contains(current.Key))
                    {
                        results.Add(new KeyValuePair<BigInteger, int>(current.Key + 1, current.Value + 1));

                        if (current.Key != 1)
                        {
                            BigInteger toPower = 1;
                            List<BigInteger> powers = new List<BigInteger>();
                            while (toPower <= desired - 1)
                            {
                                toPower *= current.Key;
                                powers.Add(toPower);
                            }

                            powers.Reverse();

                            foreach (var item in powers)
                            {
                                if (item <= desired + 1 && !used.Contains(item))
                                {
                                    if (!used.Contains(item))
                                    {
                                        results.Add(new KeyValuePair<BigInteger, int>(item, current.Value + 1));
                                    }

                                    if (!used.Contains(item - 1))
                                    {
                                        results.Add(new KeyValuePair<BigInteger, int>(item - 1, current.Value + 2));
                                    }
                                }
                            }
                        }

                        used.Add(current.Key);
                    }
                }

                Console.WriteLine(current.Value);
            }
        }
コード例 #5
0
        static public Questionnaire Run()
        {
            Questionnaire questionnaire = new Questionnaire();
            OrderedBag<Grille> OPEN = new OrderedBag<Grille>();
            OrderedBag<Grille> CLOSE = new OrderedBag<Grille>();
            Grille S = new Grille();
            OPEN.Add(S);
            while (OPEN.Count != 0)
            {
                Grille n = OPEN.RemoveFirst();
                CLOSE.Add(n);
                questionnaire.solutionsExplorer.Add(n.getStringEtat());
                if (n.getDistanceSolution() == 0)
                {
                    questionnaire.solutionMot = n.getSolutionMot();
                    questionnaire.solutionVisuelle = n.getSolutionVisuelle();
                    for (int i = 0; i < questionnaire.solutionVisuelle.Count; i++)
                    {

                        Console.Write("\n---Étape" + i + "----\n" +  questionnaire.solutionVisuelle[i] + "----------");
                    }
                    return questionnaire;
                }
                foreach (Grille nPrime in n.getListSuccessor())
                {
                    questionnaire.etatExplorer.Add(nPrime.getStringEtat());
                    if (Contient(OPEN, nPrime) != -1)
                    {
                        int position = Contient(OPEN, nPrime);
                        if (nPrime.getTotalDistance() < OPEN[position].getTotalDistance())
                        {
                            OPEN.Remove(OPEN[position]);
                            OPEN.Add(nPrime);
                        }
                    }
                    else if (Contient(CLOSE, nPrime) != -1)
                    {
                        int position = Contient(CLOSE, nPrime);
                        if (nPrime.getTotalDistance() < CLOSE[position].getTotalDistance())
                        {
                            CLOSE.Remove(CLOSE[position]);
                            OPEN.Add(nPrime);
                        }
                    }
                    else // Ni dans Close , ni dans OPEN
                    {
                        OPEN.Add(nPrime);
                    }
                }
            }
            questionnaire.solutionMot = "Aucun chemin possible";
            return questionnaire;
        }
コード例 #6
0
        public static long GetMinimalConnectionCost(string[] input)
        {
            var graph = new Dictionary<int, List<Edge>>();

            foreach (var edge in input)
            {
                var parts = edge.Split();
                var from = int.Parse(parts[0]);
                var to = int.Parse(parts[1]);
                var cost = int.Parse(parts[2]);

                InitializeIfNeeded(graph, from);
                InitializeIfNeeded(graph, to);

                graph[from].Add(new Edge(from, to, cost));
                graph[to].Add(new Edge(to, from, cost));
            }

            var startNode = graph.First().Key;

            var priorityQueue = new OrderedBag<Edge>();

            foreach (var neighbour in graph[startNode])
            {
                priorityQueue.Add(neighbour);
            }

            var cables = new List<Edge>();

            var visitedNodes = new HashSet<int> { startNode };

            while (priorityQueue.Count > 0)
            {
                var min = priorityQueue.RemoveFirst();

                if (visitedNodes.Contains(min.To))
                {
                    continue;
                }

                cables.Add(min);

                visitedNodes.Add(min.To);

                foreach (var neighbour in graph[min.To])
                {
                    priorityQueue.Add(neighbour);
                }
            }

            return cables.Sum(c => c.Cost);
        }
コード例 #7
0
        static void DijkstraFindMinCableLengthBetweenHouses(Dictionary<HouseNode, 
            List<CableConnection>> graph, HouseNode houseToStartFrom)
        {
            OrderedBag<HouseNode> houseQueue = new OrderedBag<HouseNode>();

            foreach (var house in graph)
            {
                house.Key.MinCableLenth = int.MaxValue;
            }

            houseToStartFrom.MinCableLenth = 0;
            houseQueue.Add(houseToStartFrom);

            while (houseQueue.Count > 0)
            {
                var currentHouse = houseQueue.RemoveFirst();

                if (currentHouse.MinCableLenth == int.MaxValue)
                {
                    break;
                }

                foreach (var connection in graph[currentHouse])
                {
                    var currentCableLength = currentHouse.MinCableLenth + connection.CableLenth;
                    if (connection.House.MinCableLenth > currentCableLength)
                    {
                        connection.House.MinCableLenth = currentCableLength;
                        houseQueue.Add(connection.House);
                    }
                }
            }
        }
コード例 #8
0
        public static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\students.txt");
            using (reader)
            {
                SortedDictionary<string, OrderedBag<Student>> students = new SortedDictionary<string, OrderedBag<Student>>();
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    var input = line.Split('|');
                    if (!students.ContainsKey(input[2].Trim()))
                    {
                        var grouped = new OrderedBag<Student>();
                        grouped.Add(new Student(input[0].Trim(), input[1].Trim()));
                        students.Add(input[2].Trim(), grouped);
                    }
                    else
                    {
                        students[input[2].Trim()].Add(new Student(input[0].Trim(), input[1].Trim()));
                    }
                }

                foreach (var student in students)
                {
                    Console.WriteLine(student);
                }
            }
        }
コード例 #9
0
        public static void Main()
        {
            OrderedBag<Product> catalog = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                catalog.Add(new Product("Product" + i, GetRandomNumber(39,709)));
            }
            var prices = catalog.FindAll(x => x.Price > 200 && x.Price < 350);

            
            int count = 20;
            StringBuilder sb = new StringBuilder();
            foreach (var product in prices)
            {
                sb.AppendFormat("name: {0} -> price {1}", product.Name, product.Price);
                sb.AppendLine();
               
                count -= 1;
                if (count <= 0)
                {
                    break;
               }
            }
            Console.WriteLine("Print results: ");
            Console.WriteLine(sb.ToString());
        }
コード例 #10
0
 public static void AddProductsToBag(OrderedBag<Product> orderedBag, int numberOfItems)
 {
     for (int i = 1; i < numberOfItems; i++)
     {
         orderedBag.Add(new Product(i.ToString(), i));
     }
 }
コード例 #11
0
        public static void Main()
        {
            var products = new OrderedBag<Product>();
            var builder = new StringBuilder();
            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                var productPriceTokens = Console.ReadLine().Split();
                var name = productPriceTokens[0];
                var price = float.Parse(productPriceTokens[1]);

                products.Add(new Product(name, price));
            }

            var pricesTokens = Console.ReadLine().Split();
            var lower = float.Parse(pricesTokens[0]);
            var upper = float.Parse(pricesTokens[1]);

            var subrangeProducts = products.Range(new Product(string.Empty, lower), true, new Product(string.Empty, upper), true);

            foreach (var product in subrangeProducts)
            {
                Console.WriteLine(product.ToString());
            }
        }
コード例 #12
0
        private static void SolveWithBag()
        {
            Console.WriteLine("---Bag---");
            OrderedBag<Product> bag = new OrderedBag<Product>();
            var sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < itemsCount; i++)
            {
                var price = rnd.Next(1, itemsCount);
                bag.Add(new Product(GetRandomString(), GetRandomString(), GetRandomString(), price));
            }
            Console.WriteLine("Added {0} items in {1} time", itemsCount, sw.Elapsed);

            sw.Restart();
            var secondWatch = new Stopwatch();
            for (int i = 0; i < searchesCount; i++)
            {
                var lowerProduct = new Product(GetRandomString(), GetRandomString(), GetRandomString(), rnd.Next(1, itemsCount / 2));
                var upperProduct = new Product(GetRandomString(), GetRandomString(), GetRandomString(), rnd.Next(1, itemsCount / 2));

                secondWatch.Start();
                bag.Range(lowerProduct, true, upperProduct, true);
                secondWatch.Stop();
            }
            Console.WriteLine("Found Range {0} items in {1} time", searchesCount, sw.Elapsed);
            Console.WriteLine("Actual time spent getting the Range : {0}", secondWatch.Elapsed);
        }
コード例 #13
0
        public static void Main()
        {
            myWatch.Start();
            
            Random randomGen = new Random();
            OrderedBag<Product> myBag = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                myBag.Add(new Product("Product" + i, randomGen.Next(1, 1000000)));
            }

            int start = 0;
            int end = 1000;
            for (int i = 0; i < 10000; i++)
            {
                var subBag = myBag.Range(new Product(string.Empty, start), true, new Product(string.Empty, end), true);
                IList<Product> firstTwenty = GetFirstResults(subBag);

                ////Console.WriteLine("Results");
                ////foreach (Product product in firstTwenty)
                ////{
                ////    Console.WriteLine(product);
                ////}

                start += 10;
                end += 10;
            }

            myWatch.Stop();
            Console.WriteLine("END");
            Console.WriteLine("Time: {0}", myWatch.Elapsed);
        }
コード例 #14
0
 private static void AddProducts(OrderedBag<Product> orderedBag)
 {
     for (int i = 0; i < ProductsCount; i++)
     {
         orderedBag.Add(new Product("Product " + (i + 1), GetRandomNumber(10, 17500) + (decimal)i / 100));
     }
 }
コード例 #15
0
        static void Main()
        {
            OrderedBag<Product> bag = new OrderedBag<Product>();
            Random rand = new Random();
            for (int i = 0; i < CountProducts; i++)
            {
                bag.Add(GetRandomProduct(rand));
            }

            decimal minPrice = 0M;
            for (int i = 0; i < PriceSearches; i++)
            {
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                decimal maxPrice = minPrice + 100M;
                var result = GetProductsInPriceRange(bag, minPrice, maxPrice);
                Console.WriteLine(new string('$', 79));
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("First 20 Products in Price Range {0:C} - {1:C}: ", minPrice, maxPrice);
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                if (result.Count() < 1) { Console.Write("None\n"); }
                Console.WriteLine(string.Join(" | ", result));
                minPrice += 100;
                Thread.Sleep(500);
            }
        }
コード例 #16
0
        static void Main()
        {
            var collection = new OrderedBag<Product>();
            int numberOfProducts = 500000;
            int numberOfProductsToTake = 10000;

            Console.WriteLine("Products generation started");
            for (var i = 0; i < numberOfProducts; i++)
            {
                var product = new Product("Product #" + i, (decimal)i);
                collection.Add(product);
            }
            Console.WriteLine("Products generated");

            var stringBuilder = new StringBuilder();

            Console.WriteLine("Collecting products...");
            for (var i = 0; i < numberOfProductsToTake; i++)
            {
                var rangeOfProducts =
                    collection.Range(new Product("StartSearchProduct", 154000m), true, new Product("EndSearchProduct", 155000m), true)
                        .Take(20);
                stringBuilder.AppendLine(string.Join(", ", rangeOfProducts.Select(p => p.ToString())));
            }

            Console.WriteLine(stringBuilder.ToString());
        }
コード例 #17
0
    internal static void Main()
    {
        var myStore = new OrderedBag<Product>();
        var ran = new Random();
        for (int i = 0; i < 500000; i++)
        {
            myStore.Add(new Product("prod." + ran.Next(1, 500001), ran.Next(1, 10011) / 100m));
        }

        var result = new StringBuilder();
        for (int i = 0; i < 10000; i++)
        {
            var prodList = myStore.Range(new Product(string.Empty, i + 1), true, new Product(string.Empty, i + 2), true);
            var counter = 0;
            foreach (var item in prodList)
            {
                if (counter == 20)
                {
                    break;
                }

                result.AppendFormat("{3}. Product: {0} Price: {1} BGN {2}", item.Name, item.Price, Environment.NewLine, counter + 1);
                counter++;
            }
        }

        Console.WriteLine(result);
    }
コード例 #18
0
        public static void Main(string[] args)
        {
            OrderedBag<Product> products = new OrderedBag<Product>();
            Random randomNumberGenerator = new Random();
            double randomNumber;
            for (int i = 0; i < 500000; i++)
            {
                randomNumber = randomNumberGenerator.NextDouble() * MaxValue;
                Product product = new Product("product" + i, randomNumber);
                products.Add(product);
            }

            double from;
            double to;
            for (int i = 0; i < 10000; i++)
            {
                from = randomNumberGenerator.NextDouble() * MaxValue;
                to = randomNumberGenerator.NextDouble() * MaxValue;
                var productInRange = products.Range(new Product("searchFrom", from), true, new Product("searchTo", to), true);
                foreach (var item in productInRange.Take(20))
                {
                    Console.Write("[{0} => {1}] ", item.Name, Math.Round(item.Price, 2));
                }

                Console.WriteLine();
            }
        }
コード例 #19
0
    static void Main()
    {
        const int PRODUCT_SEARCH = 20;

        OrderedBag<Item> bag = new OrderedBag<Item>();
        Random rand = new Random();

        for (int i = 0; i < 500000; i++)
        {
            bag.Add(new Item("ItemID: " + rand.Next(), rand.Next()));
        }

        var find = bag.Range(new Item("test", 0), true, new Item("test", 10000), true);

        int count = find.Count;
        if (count > PRODUCT_SEARCH)
        {
            count = PRODUCT_SEARCH;
        }

        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("{0} ==== Price: {1}", find[i].Name, find[i].Price);
        }
    }
コード例 #20
0
    static void Main()
    {
        Console.WriteLine("Generating product's list...");
        var produkts = new OrderedBag<Product>();
        Random rnd = new Random();
        for (int i = 0; i < 500000; i++)
        {
            int price = rnd.Next(1, 100001);
            string name = "product-" + i;
            Product product = new Product(name, price);
            produkts.Add(product);
        }

        Console.WriteLine("Searching 20 products in range 10257 - 11336 lv");
        Predicate<Product> isProduktInRange = p => p.Price >= 10257 && p.Price <= 11336;
        var range = produkts.FindAll(isProduktInRange);
        int count = 0;
        foreach (var item in range)
        {
            Console.WriteLine(item);
            ++count;
            if (count == 20)
            {
                return;
            }
        }
    }
コード例 #21
0
    public static void Main()
    {
        OrderedBag<Product> test = new OrderedBag<Product>();
        string originalName = "Product";
        decimal originalPrice = 1;
        Product productToAdd;

        for (int i = 0; i < 500000; i++)
        {
            productToAdd = new Product(originalName + i, originalPrice + i);
            test.Add(productToAdd);
        }

        int numberOfRangeChecks = 0;
        List<Product> topTwentyProductsInRange = new List<Product>();

        for (int i = 0, j = 10000; i < 10000; i++, j += 10)
        {
            var productsInRange = test.Range(new Product("", i), true, new Product("", j), true);

            for (int k = 0; k < 20; k++)
			{
                topTwentyProductsInRange.Add(productsInRange[k]);
			}

            numberOfRangeChecks++;
        }
    }
コード例 #22
0
ファイル: Program.cs プロジェクト: nzhul/TelerikAcademy
        static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 1; i < 500000; i++)
            {
                Product p = new Product();
                p.Name = "Prodcut" + i;
                p.Price = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                products.Add(p);
            }

            stopwatch.Stop();
            Console.WriteLine("Create and Add 500k products: {0}", stopwatch.Elapsed);

            List<Product> prodRange = new List<Product>();
            stopwatch.Reset();
            stopwatch.Restart();

            for (int i = 1; i <= 10000; i++)
            {
                int min = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                int max = GetRandomNumber(35, 599) * i * 13 * GetRandomNumber(3, 5);

                prodRange.AddRange(products.Range(new Product() { Price = min }, true, new Product() { Price = max }, true).Take(20));
            }

            stopwatch.Stop();
            Console.WriteLine("Search for 10k random price ranges: {0}", stopwatch.Elapsed);
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: damy90/Telerik-all
        static void Main(string[] args)
        {
            OrderedBag<Item> store = new OrderedBag<Item>();

            Random rnd = new Random();
            for (int i = 0; i < 500000; i++)
            {
                Item item = new Item("Product " + i, RandomPrice(rnd));
                store.Add(item);
            }

            var sw = new Stopwatch();
            sw.Start();

            IEnumerable<Item> searches = new List<Item>();
            for (int i = 0; i < 10000; i++)
            {
                double minPrice = RandomPrice(rnd);
                double maxPrice = RandomPrice(rnd);
                if (minPrice > maxPrice)
                {
                    double t = minPrice;
                    minPrice = maxPrice;
                    maxPrice = t;
                }

                searches = store.Range(new Item(minPrice), true, new Item(maxPrice), true).Take(20);
            }

            sw.Stop();

            Console.WriteLine("The time for 10 000 searches is:" + sw.Elapsed + "\nThe last result:\n" + string.Join("\n", searches));
        }
コード例 #24
0
ファイル: Startup.cs プロジェクト: VDGone/TelerikAcademy-1
        public static void Main()
        {
            string[] stringValues = new string[500000];
            for (int i = 0; i < 500000; i++)
            {
                stringValues[i] = RandomString(5);
            }

            decimal[] numberValues = new decimal[500000];
            for (int i = 0; i < 500000; i++)
            {
                numberValues[i] = GetRandomNumber(1, 1000);
            }

            OrderedBag<Product> products = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                products.Add(new Product
                {
                    Name = stringValues[i],
                    Price = numberValues[i]
                });
            }

            Console.WriteLine("Products added!");

            TestOrderBagSearchSpeed(products);
        }
コード例 #25
0
        public static void Main()
        {
            var collectionOfProducts = new OrderedBag<Product>();

            for (int i = 0; i < NumberOfProducts; i++)
            {
                var product = new Product(RandomGenerator.GetRandomStringWithRandomLength(3, 7),
                    RandomGenerator.RandomDecimalBetween(1, 100));
                collectionOfProducts.Add(product);
            }

            Console.WriteLine("{0} products have been generated!", NumberOfProducts);

            var testSearch = new List<Product>();

            Console.WriteLine("Running {0} searches:", NumberOfSearches);
            for (int i = 0; i < NumberOfSearches; i++)
            {
                testSearch = SearchProductsByRange(collectionOfProducts, RandomGenerator.RandomDecimalBetween(1, 10),
                    RandomGenerator.RandomDecimalBetween(11, 100));

                if (i%100 == 0)
                {
                    Console.Write("=");
                }
            }

            Console.WriteLine("\r\nTotal products matching the last search criteria: {0}", testSearch.Count);
            Console.WriteLine("First 20 products:");
            foreach (var product in testSearch.Take(20))
            {
                Console.WriteLine(product);
            }
        }
コード例 #26
0
        public static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                var newProduct = new Product()
                {
                    Name = string.Format("Product #{0}", i + 1),
                    Price = Math.Round((decimal)(random.NextDouble() * 10000), 2)
                };

                products.Add(newProduct);
            }


            var priceFrom = 999;
            var PriceTo = 1000;
            Console.WriteLine("Sub-range [{0}...{1}]: ", priceFrom, PriceTo);
            var result = products.Range(new Product() { Price = priceFrom }, true, new Product() { Price = PriceTo}, true);

            foreach(var product in result)
            {
                Console.WriteLine(product);
            }
        }
        public static void Main(string[] args)
        {
            var data = new OrderedBag<Product>();

            Console.WriteLine("Creating random products");
            for (int i = 0; i < ProductCount; i++)
            {
                data.Add(
                    new Product(
                        RandomGenerator.RandomString(RandomGenerator.RandomInt(1, 100)),
                        (double)(RandomGenerator.RandomInt(1, 100000)) / 100));
            }

            Console.WriteLine("Searching products");
            for (int i = 0; i < SearchCount; i++)
            {
                double minValue = RandomGenerator.RandomInt(1, 100);
                double maxValue = RandomGenerator.RandomInt((int)minValue, (int)minValue + 900);

                var range = data.Range(new Product("", minValue), true, new Product("", maxValue), true);
                Console.WriteLine("Search #" + i);

                for (int j = 0; j < 20; j++)
                {
                    Console.WriteLine("Item# " + j + " = " + range[j].Name);
                }
            }
        }
コード例 #28
0
        static void DijkstraAlgorithm(Node[] graph, Node source)
        {
            var priority = new OrderedBag<Node>();

            for (int i = 1; i < graph.Length; i++)
            {
                graph[i].DijkstraDistance = int.MaxValue;
            }

            source.DijkstraDistance = 0;
            priority.Add(source);

            while (priority.Count != 0)
            {
                Node currentNode = priority.RemoveFirst();

                if (currentNode.DijkstraDistance == int.MaxValue)
                {
                    break;
                }

                for (int i = 0; i < currentNode.Edges.Count; i++)
                {
                    int potDistance = currentNode.DijkstraDistance + currentNode.Edges[i].Weight;

                    if (potDistance < graph[currentNode.Edges[i].NodeId].DijkstraDistance)
                    {
                        graph[currentNode.Edges[i].NodeId].DijkstraDistance = potDistance;
                        priority.Add(graph[currentNode.Edges[i].NodeId]);
                    }
                }
            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: niki-funky/Telerik_Academy
        private static void GetData(
            ref SortedDictionary<string, OrderedBag<Student>> listOfCourses,
            string fileName)
        {
            string line;
            using (StreamReader reader = new StreamReader(fileName))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    var entry = line.Split('|');

                    var fName = entry[0].Trim();
                    var lName = entry[1].Trim();
                    var course = entry[2].Trim();

                    Student student = new Student(fName, lName, course);

                    if (!listOfCourses.ContainsKey(course))
                    {
                        OrderedBag<Student> listOfStudents = new OrderedBag<Student>();
                        listOfStudents.Add(student);
                        listOfCourses.Add(course, listOfStudents);
                    }
                    else
                    {
                        listOfCourses[course].Add(student);
                    }
                }
            }
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: vaster/Telerik.vasko
        static void Main(string[] args)
        {
            OrderedBag<ComparableKeyValuePair<string, int>> catalog =
                new OrderedBag<ComparableKeyValuePair<string, int>>();

            for (int i = 0; i < 25; i++)
            {
                ComparableKeyValuePair<string, int> item = new ComparableKeyValuePair<string, int>(i.ToString(), i);
                catalog.Add(item);
            }

            ComparableKeyValuePair<string, int> downRange = new ComparableKeyValuePair<string, int>("3", 3);
            ComparableKeyValuePair<string, int> upRange = new ComparableKeyValuePair<string, int>("23", 23);

            OrderedBag<ComparableKeyValuePair<string, int>>.View range = catalog.Range(downRange, true, upRange, true);
            Console.WriteLine("from 3");
            foreach (ComparableKeyValuePair<string, int> item in range)
            {
                Console.WriteLine(item.Value);
            }
            Console.WriteLine("to 23");


            // Test for 500 000 products and 10 000 price searches.

            catalog =
                new OrderedBag<ComparableKeyValuePair<string, int>>();

            Stopwatch timer = new Stopwatch();

            timer.Start();

            for (int i = 0; i <= 500000; i++)
            {
                ComparableKeyValuePair<string, int> item = new ComparableKeyValuePair<string, int>(i.ToString(), i);
                catalog.Add(item);
            }
            Console.WriteLine("Adding 500 000 elements: " + timer.Elapsed.TotalSeconds + " sec");
           

            OrderedBag<ComparableKeyValuePair<string, int>>.View bigRange = null;

            ComparableKeyValuePair<string, int> from = new ComparableKeyValuePair<string, int>("400000", 400000);
            ComparableKeyValuePair<string, int> to = new ComparableKeyValuePair<string, int>("410000", 410000);

            timer.Reset();
            timer.Start();

            for (int i = 10000; i <= 400000; i = i + 20)
            {
                bigRange = catalog.Range(from, true, to, false);

                from = new ComparableKeyValuePair<string, int>((i - 20).ToString(), (i - 20));
                to = new ComparableKeyValuePair<string, int>(i.ToString(), i);
            }

            Console.WriteLine("10 000 searches (200 000 to 400 000):" + timer.Elapsed.TotalMilliseconds + " ms");

            timer.Stop();
        }
コード例 #31
0
        private static void ExecuteCommand(string[] command)
        {
            if (command[0] == "add")
            {
                if (!productNames.Contains(command[1]))
                {
                    var product = new Product(command[1], double.Parse(command[2]), command[3]);
                    products.Add(product);
                    productNames.Add(command[1]);

                    if (!typeProducts.ContainsKey(command[3]))
                    {
                        typeProducts.Add(command[3], new OrderedBag <Product>());
                    }

                    typeProducts[command[3]].Add(product);

                    Console.WriteLine("Ok: Product {0} added successfully", product.Name);
                }
                else
                {
                    Console.WriteLine("Error: Product {0} already exists", command[1]);
                }
            }
            else if (command[0] == "filter" && command.Length == 7)
            {
                var items = products.Where(x => x.Price >= double.Parse(command[4]) && x.Price <= double.Parse(command[6])).Take(10);
                if (items.Count() == 0)
                {
                    Console.WriteLine("Ok: ");
                }
                else
                {
                    Console.WriteLine("Ok: " + string.Join(", ", items));
                }
            }
            else if (command[0] == "filter" && command.Length == 5)
            {
                if (command[3] == "from")
                {
                    var items = products.Where(x => x.Price >= double.Parse(command[4])).Take(10);
                    if (items.Count() == 0)
                    {
                        Console.WriteLine("Ok: ");
                    }
                    else
                    {
                        Console.WriteLine("Ok: " + string.Join(", ", items));
                    }
                }
                else if (command[3] == "to")
                {
                    var items = products.Where(x => x.Price <= double.Parse(command[4])).Take(10);
                    if (items.Count() == 0)
                    {
                        Console.WriteLine("Ok: ");
                    }
                    else
                    {
                        Console.WriteLine("Ok: " + string.Join(", ", items));
                    }
                }
            }
            else if (command[0] == "filter" && command.Length == 4)
            {
                if (typeProducts.ContainsKey(command[3]))
                {
                    var    items  = typeProducts[command[3]].Take(10);
                    string output = string.Join(", ", items);
                    Console.WriteLine("Ok: " + output);
                }
                else
                {
                    Console.WriteLine("Error: Type {0} does not exists", command[3]);
                }
            }
        }
コード例 #32
0
ファイル: Program.cs プロジェクト: dpenkova/TelerikAcademy-3
        static void Main()
        {
            var nmh = Console.ReadLine().Trim().Split().Select(int.Parse).ToArray();

            var hospitalsString = Console.ReadLine().Split();

            var hospitals = new HashSet <int>();

            foreach (var hospStr in hospitalsString)
            {
                hospitals.Add(int.Parse(hospStr));
            }

            var graph = new Dictionary <int, Node>();

            var line = new string[2];
            var from = 0;
            var to   = 0;
            var dist = 0;

            var maxDistance = 99999999;

            for (int i = 0; i < nmh[1]; i++)
            {
                line = Console.ReadLine().Split();
                from = int.Parse(line[0]);
                to   = int.Parse(line[1]);
                dist = int.Parse(line[2]);

                if (!graph.ContainsKey(from))
                {
                    graph.Add(from, new Node(from));
                }

                if (!graph.ContainsKey(to))
                {
                    graph.Add(to, new Node(to));
                }

                graph[from].connections.Add(to, dist);
                graph[to].connections.Add(from, dist);
            }

            long answer = long.MaxValue;

            foreach (var hosp in hospitals)
            {
                var bag = new OrderedBag <Node>();

                foreach (var kv in graph)
                {
                    graph[kv.Key].diikstra = maxDistance;
                    bag.Add(graph[kv.Key]);
                }

                graph[hosp].diikstra = 0;

                while (bag.Count > 0)
                {
                    var min = bag.GetFirst();

                    foreach (var kv in min.connections)
                    {
                        var potDistance = min.diikstra + kv.Value;
                        if (potDistance < graph[kv.Key].diikstra)
                        {
                            graph[kv.Key].diikstra = potDistance;
                            bag.Add(graph[kv.Key]);
                        }
                    }

                    bag.RemoveFirst();
                }

                long currentSum = 0;
                foreach (var kv in graph)
                {
                    if (!hospitals.Contains(kv.Key))
                    {
                        currentSum += graph[kv.Key].diikstra;
                    }
                }

                if (answer > currentSum)
                {
                    answer = currentSum;
                }
            }

            Console.WriteLine(answer);
        }
コード例 #33
0
ファイル: Collision.cs プロジェクト: travv0/STG
        /// <summary>
        /// Uses separating axis theorem to determine if there is a collision
        /// </summary>
        /// <param name="o1">verticies of an object</param>
        /// <param name="o2">main playing area</param>
        /// <returns></returns>
        public Boolean collides(List <Vector2> o1, Rectangle o2)
        {
            //finding axes
            Vector2 axis1, axis2, axis3, axis4;

            axis1.X = o1[1].X - o1[0].X;
            axis1.Y = o1[1].Y - o1[0].Y;
            axis2.X = o1[1].X - o1[3].X;
            axis2.Y = o1[1].Y - o1[3].Y;
            axis3.X = o2.X - o2.X;
            axis3.Y = o2.Y - (o2.Y + o2.Height);
            axis4.X = o2.X - (o2.X + o2.Width);
            axis4.Y = o2.Y - o2.Y;

            //checking if overlap on axis1
            float scalarUR = (axis1.X * 2) * ((o1[1].X * axis1.X + o1[1].Y * axis1.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y)) + (axis1.Y * 2) * ((o1[1].X * axis1.X + o1[1].Y * axis1.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y));
            float scalarUL = (axis1.X * 2) * ((o1[0].X * axis1.X + o1[0].Y * axis1.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y)) + (axis1.Y * 2) * ((o1[0].X * axis1.X + o1[0].Y * axis1.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y));
            float scalarBR = (axis1.X * 2) * ((o1[3].X * axis1.X + o1[3].Y * axis1.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y)) + (axis1.Y * 2) * ((o1[3].X * axis1.X + o1[3].Y * axis1.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y));
            float scalarBL = (axis1.X * 2) * ((o1[2].X * axis1.X + o1[2].Y * axis1.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y)) + (axis1.Y * 2) * ((o1[2].X * axis1.X + o1[2].Y * axis1.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y));
            float maxA, minA, maxB, minB;
            OrderedBag <float> scalars = new OrderedBag <float>();

            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minA = scalars[0];
            maxA = scalars[3];

            scalarUR = (axis1.X * 2) * (((o2.X + o2.Width) * axis1.X + o2.Y * axis1.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y)) + (axis1.Y * 2) * (((o2.X + o2.Width) * axis1.X + o2.Y * axis1.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y));
            scalarUL = (axis1.X * 2) * ((o2.X * axis1.X + o2.Y * axis1.Y) / (o2.X * o2.X + o2.Y * o2.Y)) + (axis1.Y * 2) * ((o2.X * axis1.X + o2.Y * axis1.Y) / (o2.X * o2.X + o2.Y * o2.Y));
            scalarBR = (axis1.X * 2) * (((o2.X + o2.Width) * axis1.X + o1[3].Y * axis1.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis1.Y * 2) * (((o2.X + o2.Width) * axis1.X + (o2.Y + o2.Height) * axis1.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalarBL = (axis1.X * 2) * ((o2.X * axis1.X + (o2.Y + o2.Height) * axis1.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis1.Y * 2) * ((o2.X * axis1.X + (o2.Y + o2.Height) * axis1.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minB = scalars[0];
            maxB = scalars[3];
            if (!(minB <= minA && maxB >= minA))
            {
                return(false);
            }
            //end checking for overlap on axis1;

            //checking if overlap on axis2
            scalarUR = (axis2.X * 2) * ((o1[1].X * axis2.X + o1[1].Y * axis2.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y)) + (axis2.Y * 2) * ((o1[1].X * axis2.X + o1[1].Y * axis2.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y));
            scalarUL = (axis2.X * 2) * ((o1[0].X * axis2.X + o1[0].Y * axis2.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y)) + (axis2.Y * 2) * ((o1[0].X * axis2.X + o1[0].Y * axis2.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y));
            scalarBR = (axis2.X * 2) * ((o1[3].X * axis2.X + o1[3].Y * axis2.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y)) + (axis2.Y * 2) * ((o1[3].X * axis2.X + o1[3].Y * axis2.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y));
            scalarBL = (axis2.X * 2) * ((o1[2].X * axis2.X + o1[2].Y * axis2.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y)) + (axis2.Y * 2) * ((o1[2].X * axis2.X + o1[2].Y * axis2.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minA = scalars[0];
            maxA = scalars[3];

            scalarUR = (axis2.X * 2) * (((o2.X + o2.Width) * axis2.X + o2.Y * axis2.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y)) + (axis2.Y * 2) * (((o2.X + o2.Width) * axis2.X + o2.Y * axis2.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y));
            scalarUL = (axis2.X * 2) * ((o2.X * axis2.X + o2.Y * axis2.Y) / (o2.X * o2.X + o2.Y * o2.Y)) + (axis2.Y * 2) * ((o2.X * axis2.X + o2.Y * axis2.Y) / (o2.X * o2.X + o2.Y * o2.Y));
            scalarBR = (axis2.X * 2) * (((o2.X + o2.Width) * axis2.X + o1[3].Y * axis2.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis2.Y * 2) * (((o2.X + o2.Width) * axis2.X + (o2.Y + o2.Height) * axis2.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalarBL = (axis2.X * 2) * ((o2.X * axis2.X + (o2.Y + o2.Height) * axis2.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis2.Y * 2) * ((o2.X * axis2.X + (o2.Y + o2.Height) * axis2.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minB = scalars[0];
            maxB = scalars[3];
            if (!(minB <= minA && maxB >= minA))
            {
                return(false);
            }
            //end checking for overlap on axis2;

            //checking if overlap on axis3
            scalarUR = (axis3.X * 2) * ((o1[1].X * axis3.X + o1[1].Y * axis3.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y)) + (axis3.Y * 2) * ((o1[1].X * axis3.X + o1[1].Y * axis3.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y));
            scalarUL = (axis3.X * 2) * ((o1[0].X * axis3.X + o1[0].Y * axis3.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y)) + (axis3.Y * 2) * ((o1[0].X * axis3.X + o1[0].Y * axis3.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y));
            scalarBR = (axis3.X * 2) * ((o1[3].X * axis3.X + o1[3].Y * axis3.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y)) + (axis3.Y * 2) * ((o1[3].X * axis3.X + o1[3].Y * axis3.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y));
            scalarBL = (axis3.X * 2) * ((o1[2].X * axis3.X + o1[2].Y * axis3.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y)) + (axis3.Y * 2) * ((o1[2].X * axis3.X + o1[2].Y * axis3.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minA = scalars[0];
            maxA = scalars[3];

            scalarUR = (axis3.X * 2) * (((o2.X + o2.Width) * axis3.X + o2.Y * axis3.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y)) + (axis3.Y * 2) * (((o2.X + o2.Width) * axis3.X + o2.Y * axis3.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y));
            scalarUL = (axis3.X * 2) * ((o2.X * axis3.X + o2.Y * axis3.Y) / (o2.X * o2.X + o2.Y * o2.Y)) + (axis3.Y * 2) * ((o2.X * axis3.X + o2.Y * axis3.Y) / (o2.X * o2.X + o2.Y * o2.Y));
            scalarBR = (axis3.X * 2) * (((o2.X + o2.Width) * axis3.X + o1[3].Y * axis3.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis3.Y * 2) * (((o2.X + o2.Width) * axis3.X + (o2.Y + o2.Height) * axis3.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalarBL = (axis3.X * 2) * ((o2.X * axis3.X + (o2.Y + o2.Height) * axis3.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis3.Y * 2) * ((o2.X * axis3.X + (o2.Y + o2.Height) * axis3.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minB = scalars[0];
            maxB = scalars[3];
            if (!(minB <= minA && maxB >= minA))
            {
                return(false);
            }
            //end checking for overlap on axis3;

            //checking if overlap on axis4
            scalarUR = (axis4.X * 2) * ((o1[1].X * axis4.X + o1[1].Y * axis4.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y)) + (axis4.Y * 2) * ((o1[1].X * axis4.X + o1[1].Y * axis4.Y) / (o1[1].X * o1[1].X + o1[1].Y * o1[1].Y));
            scalarUL = (axis4.X * 2) * ((o1[0].X * axis4.X + o1[0].Y * axis4.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y)) + (axis4.Y * 2) * ((o1[0].X * axis4.X + o1[0].Y * axis4.Y) / (o1[0].X * o1[0].X + o1[0].Y * o1[0].Y));
            scalarBR = (axis4.X * 2) * ((o1[3].X * axis4.X + o1[3].Y * axis4.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y)) + (axis4.Y * 2) * ((o1[3].X * axis4.X + o1[3].Y * axis4.Y) / (o1[3].X * o1[3].X + o1[3].Y * o1[3].Y));
            scalarBL = (axis4.X * 2) * ((o1[2].X * axis4.X + o1[2].Y * axis4.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y)) + (axis4.Y * 2) * ((o1[2].X * axis4.X + o1[2].Y * axis4.Y) / (o1[2].X * o1[2].X + o1[2].Y * o1[2].Y));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minA = scalars[0];
            maxA = scalars[3];

            scalarUR = (axis4.X * 2) * (((o2.X + o2.Width) * axis4.X + o2.Y * axis4.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y)) + (axis4.Y * 2) * (((o2.X + o2.Width) * axis4.X + o2.Y * axis4.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + o2.Y * o2.Y));
            scalarUL = (axis4.X * 2) * ((o2.X * axis4.X + o2.Y * axis4.Y) / (o2.X * o2.X + o2.Y * o2.Y)) + (axis4.Y * 2) * ((o2.X * axis4.X + o2.Y * axis4.Y) / (o2.X * o2.X + o2.Y * o2.Y));
            scalarBR = (axis4.X * 2) * (((o2.X + o2.Width) * axis4.X + o1[3].Y * axis4.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis4.Y * 2) * (((o2.X + o2.Width) * axis4.X + (o2.Y + o2.Height) * axis4.Y) / ((o2.X + o2.Width) * (o2.X + o2.Width) + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalarBL = (axis4.X * 2) * ((o2.X * axis4.X + (o2.Y + o2.Height) * axis4.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height))) + (axis4.Y * 2) * ((o2.X * axis4.X + (o2.Y + o2.Height) * axis4.Y) / (o2.X * o2.X + (o2.Y + o2.Height) * (o2.Y + o2.Height)));
            scalars  = new OrderedBag <float>();
            scalars.Add(scalarUR);
            scalars.Add(scalarUL);
            scalars.Add(scalarBR);
            scalars.Add(scalarBL);
            minB = scalars[0];
            maxB = scalars[3];
            if (!(minB <= minA && maxB >= minA))
            {
                return(false);
            }
            //end checking for overlap on axis4;
            else
            {
                return(true);//if only one of the projected values do not overlap they do not collide
            }
        }
コード例 #34
0
        public static void Main(string[] args)
        {
            var nodesCount = int.Parse(Console.ReadLine());
            var edgesCount = int.Parse(Console.ReadLine());

            graph   = ReadGraph(nodesCount, edgesCount);
            cameras = ReadCameras(nodesCount);

            var startNode = int.Parse(Console.ReadLine());
            var endNode   = int.Parse(Console.ReadLine());

            var distances = new double[nodesCount];

            for (int i = 0; i < distances.Length; i++)
            {
                distances[i] = double.PositiveInfinity;
            }

            var queue = new OrderedBag <int>(
                Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));

            distances[startNode] = 0;
            queue.Add(startNode);

            while (queue.Count > 0)
            {
                var node = queue.RemoveFirst();

                if (node == endNode)
                {
                    break;
                }

                foreach (var edge in graph[node])
                {
                    var child = edge.First == node
                        ? edge.Second
                        : edge.First;

                    if (cameras[child])
                    {
                        continue;
                    }

                    if (double.IsPositiveInfinity(distances[child]))
                    {
                        queue.Add(child);
                    }

                    var newDistance = distances[node] + edge.Distance;

                    if (newDistance < distances[child])
                    {
                        distances[child] = newDistance;

                        queue = new OrderedBag <int>(
                            queue,
                            Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));
                    }
                }
            }

            Console.WriteLine(distances[endNode]);
        }
コード例 #35
0
 public void Push(NodeModelModel node)
 {
     priorityQueue.Add(node);
 }
コード例 #36
0
        public static long Solve(string[] input)
        {
            var graph = new Dictionary <int, List <CablePath> >();

            foreach (var connection in input)
            {
                var line = connection.Split();
                var from = int.Parse(line[0]);
                var to   = int.Parse(line[1]);
                var cost = int.Parse(line[2]);

                if (!graph.ContainsKey(from))
                {
                    graph.Add(from, new List <CablePath>());
                }

                if (!graph.ContainsKey(to))
                {
                    graph.Add(to, new List <CablePath>());
                }

                graph[from].Add(new CablePath {
                    FromHouse = from, ToHouse = to, Cost = cost
                });
                graph[to].Add(new CablePath {
                    FromHouse = to, ToHouse = from, Cost = cost
                });
            }

            var startNode = graph.First().Key;

            var bag = new OrderedBag <CablePath>();

            foreach (var neighbour in graph[startNode])
            {
                bag.Add(neighbour);
            }

            var minimumSpanningTreeCables = new List <CablePath>();

            var visitedNodes = new HashSet <int>();

            visitedNodes.Add(startNode);

            while (bag.Count > 0)
            {
                var min = bag.RemoveFirst();

                if (visitedNodes.Contains(min.ToHouse))
                {
                    continue;
                }

                minimumSpanningTreeCables.Add(min);

                visitedNodes.Add(min.ToHouse);

                foreach (var neighbour in graph[min.ToHouse])
                {
                    bag.Add(neighbour);
                }
            }

            return(minimumSpanningTreeCables.Sum(c => c.Cost));
        }
コード例 #37
0
        static void Main()
        {
            var nodeCount = int.Parse(Console.ReadLine().Split()[1]);
            var pathData  = Console.ReadLine().Split();
            var start     = int.Parse(pathData[1]);
            var end       = int.Parse(pathData[3]);
            var edgeCount = int.Parse(Console.ReadLine().Split()[1]);

            graph = new Dictionary <int, List <Edge> >();

            for (int i = 0; i < edgeCount; i++)
            {
                var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
                var edge  = new Edge
                {
                    First  = input[0],
                    Second = input[1],
                    Cost   = input[2]
                };

                if (!graph.ContainsKey(edge.First))
                {
                    graph[edge.First] = new List <Edge>();
                }

                if (!graph.ContainsKey(edge.Second))
                {
                    graph[edge.Second] = new List <Edge>();
                }

                graph[edge.First].Add(edge);
                graph[edge.Second].Add(edge);
            }

            visited        = new bool[graph.Count];
            visited[start] = true;

            prev        = new int[graph.Count];
            prev[start] = -1;

            percentages        = Enumerable.Repeat <double>(-1, graph.Count).ToArray();
            percentages[start] = 100;

            var queue = new OrderedBag <int>(
                Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));

            queue.Add(start);

            while (queue.Count > 0)
            {
                var min = queue.RemoveFirst();
                if (percentages[min] == -1)
                {
                    break;
                }

                foreach (var child in graph[min])
                {
                    var otherNode = child.First == min
                        ? child.Second
                        : child.First;

                    if (!visited[otherNode])
                    {
                        visited[otherNode] = true;
                        queue.Add(otherNode);
                    }

                    var newPerc = percentages[min] / 100 * child.Cost;

                    if (newPerc > percentages[otherNode])
                    {
                        percentages[otherNode] = newPerc;

                        prev[otherNode] = min;

                        queue = new OrderedBag <int>(
                            queue,
                            Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));
                    }
                }
            }

            var result  = new List <int>();
            var current = end;

            while (current != -1)
            {
                result.Add(current);
                current = prev[current];
            }
            result.Reverse();
            Console.WriteLine($"Most reliable path reliability: {percentages[end]:F2}%");
            Console.WriteLine(string.Join(" -> ", result));
        }
コード例 #38
0
ファイル: Dijkstra.cs プロジェクト: dpenkova/TelerikAcademy-3
        static void Main(string[] args)
        {
            var PointsStreetsHospitals = Console.ReadLine().Split().Select(int.Parse).ToArray();

            var hospitals = new HashSet <int>(Console.ReadLine().Split().Select(int.Parse));

            var graph = new Dictionary <Node, List <Edge> >();

            var dict = new Dictionary <int, Node>();

            for (int i = 0; i < PointsStreetsHospitals[1]; i++)
            {
                var connection = Console.ReadLine().Split().Select(int.Parse).ToArray();

                if (!dict.ContainsKey(connection[0]))
                {
                    var node = new Node(connection[0]);
                    dict.Add(connection[0], node);
                    graph.Add(node, new List <Edge>());
                }
                if (!dict.ContainsKey(connection[1]))
                {
                    var node = new Node(connection[1]);
                    dict.Add(connection[1], node);
                    graph.Add(node, new List <Edge>());
                }

                graph[dict[connection[0]]].Add(new Edge(dict[connection[1]], connection[2]));
                graph[dict[connection[1]]].Add(new Edge(dict[connection[0]], connection[2]));
            }

            var absoluteMin = int.MaxValue;

            foreach (var hosp in hospitals)
            {
                foreach (var kv in graph)
                {
                    kv.Key.Dijkstra = int.MaxValue;
                }

                var startNode = dict[hosp];
                startNode.Dijkstra = 0;

                var bag = new OrderedBag <Node>();
                bag.Add(startNode);

                while (bag.Count > 0)
                {
                    var min = bag.RemoveFirst();

                    if (min.Dijkstra == int.MaxValue)
                    {
                        break;
                    }

                    foreach (var edge in graph[min])
                    {
                        var pot = min.Dijkstra + edge.Weight;

                        if (pot < edge.ToNode.Dijkstra)
                        {
                            edge.ToNode.Dijkstra = pot;
                            bag.Add(edge.ToNode);
                        }
                    }
                }

                var currentSum = 0;
                foreach (var kv in dict)
                {
                    if (!hospitals.Contains(kv.Key))
                    {
                        currentSum += kv.Value.Dijkstra;
                    }
                }

                if (absoluteMin > currentSum)
                {
                    absoluteMin = currentSum;
                }
            }

            Console.WriteLine(absoluteMin);
        }
コード例 #39
0
        public override ReadOnlyCollection <Connection> FindPath(Region source_, Region dest_)
        {
            OrderedBag <Pathfinder.PathNode> orderedBag1 = new OrderedBag <Pathfinder.PathNode>((IComparer <Pathfinder.PathNode>) new AStar.NodeComparer());
            OrderedBag <Pathfinder.PathNode> orderedBag2 = new OrderedBag <Pathfinder.PathNode>((IComparer <Pathfinder.PathNode>) new AStar.NodeComparer());

            Pathfinder.PathNode pathNode1 = new Pathfinder.PathNode();
            DateTime            now       = DateTime.Now;

            pathNode1.ConnectCost   = 0.0f;
            pathNode1.EstimatedCost = 0.0f;
            pathNode1.TotalCost     = 0.0f;
            pathNode1.RegionRef     = source_;
            pathNode1.Parent        = (Pathfinder.PathNode)null;
            pathNode1.CurrentLink   = (Connection)null;
            orderedBag1.Add(pathNode1);
            while (orderedBag1.Count != 0)
            {
                Pathfinder.PathNode pathNode2 = orderedBag1.RemoveFirst();
                if (pathNode2.RegionRef == dest_)
                {
                    Pathfinder.PathNode pathNode3      = pathNode2;
                    List <Connection>   connectionList = new List <Connection>();
                    for (; pathNode3.Parent != null; pathNode3 = pathNode3.Parent)
                    {
                        connectionList.Add(pathNode3.CurrentLink);
                    }
                    connectionList.Reverse();
                    TimeSpan timeSpan = DateTime.Now - now;
                    AStar.s_log.Debug("PathFind finishTime: " + (object)timeSpan.TotalMilliseconds);
                    return(new ReadOnlyCollection <Connection>((IList <Connection>)connectionList));
                }
                int count1 = pathNode2.RegionRef.Connections.Count;
                for (int index1 = 0; index1 < count1; ++index1)
                {
                    Connection connection = pathNode2.RegionRef.Connections[index1];
                    bool       flag       = false;
                    int        count2     = orderedBag1.Count;
                    for (int index2 = 0; index2 < count2; ++index2)
                    {
                        Pathfinder.PathNode pathNode3 = orderedBag1[index2];
                        if (pathNode3.RegionRef == connection.To)
                        {
                            if ((double)pathNode2.ConnectCost + (double)connection.Distance < (double)pathNode3.ConnectCost)
                            {
                                pathNode3.ConnectCost = pathNode2.ConnectCost + connection.Distance;
                                pathNode3.TotalCost   = pathNode3.ConnectCost + pathNode3.EstimatedCost;
                                pathNode3.Parent      = pathNode2;
                                pathNode3.CurrentLink = connection;
                                orderedBag1.Remove(pathNode3);
                                orderedBag1.Add(pathNode3);
                            }
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        int count3 = orderedBag2.Count;
                        for (int index2 = 0; index2 < count3; ++index2)
                        {
                            if (orderedBag2[index2].RegionRef == connection.To)
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)
                    {
                        Pathfinder.PathNode pathNode3 = new Pathfinder.PathNode();
                        pathNode3.Parent        = pathNode2;
                        pathNode3.RegionRef     = connection.To;
                        pathNode3.ConnectCost   = pathNode2.ConnectCost + connection.Distance;
                        pathNode3.EstimatedCost = this.Heuristic(pathNode2.RegionRef, dest_);
                        pathNode3.TotalCost     = pathNode3.ConnectCost + pathNode3.EstimatedCost;
                        pathNode3.CurrentLink   = connection;
                        orderedBag1.Add(pathNode3);
                    }
                }
                orderedBag2.Add(pathNode2);
            }
            TimeSpan timeSpan1 = DateTime.Now - now;

            AStar.s_log.Debug("PathFind failed finishTime: " + (object)timeSpan1.TotalMilliseconds);
            return((ReadOnlyCollection <Connection>)null);
        }
コード例 #40
0
        private static void CalcShortestPathsDijkstra()
        {
            InitializeDistances(); // infinity
            InitializePrevNodes(); // null

            var priorityQueue = new OrderedBag <Node>(
                Comparer <Node> .Create((a, b) =>
            {
                var compare = distances[a.Row][a.Col] - distances[b.Row][b.Col];     // min distance
                if (compare == 0)
                {
                    compare = a.Row - b.Row;
                }                                                  // top to bottom
                if (compare == 0)
                {
                    compare = a.Col - b.Col;
                }                                                  // left to right
                return(compare);
            }));

            priorityQueue.Add(new Node(0, 0)); // starting node

            while (priorityQueue.Any())
            {
                var minNode = priorityQueue.RemoveFirst();

                var minNodeDistance = distances[minNode.Row][minNode.Col];
                if (minNodeDistance == Infinity)
                {
                    break; // all nodes traversed
                }

                var neighbours = GetNeighbours(minNode.Row, minNode.Col);

                foreach (var neighbour in neighbours)
                {
                    // Enqueque unvisited nodes
                    var neighbourDistance = distances[neighbour.Row][neighbour.Col];
                    if (neighbourDistance == Infinity)
                    {
                        priorityQueue.Add(neighbour);
                    }

                    // Improve distance from minNode to neighbour
                    var newDistance = minNodeDistance + matrix[neighbour.Row][neighbour.Col];
                    if (newDistance < neighbourDistance)
                    {
                        distances[neighbour.Row][neighbour.Col] = newDistance;
                        prevNodes[neighbour.Row][neighbour.Col] = minNode;

                        // Reorder Queue
                        priorityQueue = new OrderedBag <Node>(priorityQueue,
                                                              Comparer <Node> .Create((a, b) =>
                        {
                            var compare = distances[a.Row][a.Col] - distances[b.Row][b.Col];
                            if (compare == 0)
                            {
                                compare = a.Row - b.Row;
                            }
                            if (compare == 0)
                            {
                                compare = a.Col - b.Col;
                            }
                            return(compare);
                        }));
                    }
                }
            }
        }
コード例 #41
0
        static void Main(string[] args)
        {
            Dictionary <string, OrderedBag <Order> >  consumerToMap = new Dictionary <string, OrderedBag <Order> >();
            OrderedDictionary <double, List <Order> > priceToMap    = new OrderedDictionary <double, List <Order> >();

            int numberOfTurns = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfTurns; i++)
            {
                string[] commandLine = Console.ReadLine().Split(new[] { ' ' }, 2).ToArray();

                switch (commandLine[0])
                {
                case "AddOrder":
                    string[] addDetails = commandLine[1].Split(';');

                    string name     = addDetails[0];
                    double price    = double.Parse(addDetails[1]);
                    string consumer = addDetails[2];
                    Order  order    = new Order(name, consumer, price);

                    if (!priceToMap.ContainsKey(price))
                    {
                        priceToMap.Add(price, new List <Order>());
                    }
                    priceToMap[price].Add(order);

                    if (!consumerToMap.ContainsKey(consumer))
                    {
                        consumerToMap.Add(consumer, new OrderedBag <Order>());
                    }

                    consumerToMap[consumer].Add(order);

                    Console.WriteLine("Order added");
                    break;

                case "DeleteOrders":

                    if (consumerToMap.ContainsKey(commandLine[1]))
                    {
                        OrderedBag <Order> subset = consumerToMap[commandLine[1]];
                        foreach (Order set in subset)
                        {
                            priceToMap[set.Price].Remove(set);
                        }
                        consumerToMap.Remove(commandLine[1]);

                        Console.WriteLine(subset.Count + " orders deleted");
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }
                    break;

                case "FindOrdersByPriceRange":
                    string[] priceDetails = commandLine[1].Split(';');

                    double min = double.Parse(priceDetails[0]);
                    double max = double.Parse(priceDetails[1]);

                    OrderedBag <Order> priceBetweenMinMax = new OrderedBag <Order>();

                    foreach (var items in priceToMap.Range(min, true, max, true).Values)
                    {
                        foreach (var item in items)
                        {
                            priceBetweenMinMax.Add(item);
                        }
                    }

                    if (priceBetweenMinMax.Any())
                    {
                        foreach (Order item in priceBetweenMinMax)
                        {
                            Console.WriteLine(item);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }

                    break;

                case "FindOrdersByConsumer":
                    if (consumerToMap.ContainsKey(commandLine[1]))
                    {
                        foreach (Order purchase in consumerToMap[commandLine[1]])
                        {
                            Console.WriteLine(purchase);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }
                    break;
                }
            }
        }
コード例 #42
0
        static void Main(string[] args)
        {
            string        input  = Console.ReadLine();
            StringBuilder result = new StringBuilder();

            while (input != "EXIT")
            {
                string[] inputSplit = input.Split();
                string   command    = inputSplit[0];

                if (command == "ADD")
                {
                    short number = short.Parse(inputSplit[1]);

                    if (set2.Count == 0)
                    {
                        set2.Enqueue(number);
                        totalSoFar++;
                        input = Console.ReadLine();
                        continue;
                    }

                    if (number > set2.Peek())
                    {
                        set2.Enqueue(number);
                        totalSoFar++;
                    }
                    else
                    {
                        set1.Add(number);
                        totalSoFar++;
                    }

                    if (set2.Count > set1.Count + 1)
                    {
                        short min = set2.Dequeue();

                        set1.Add(min);
                    }
                    else if (set2.Count < set1.Count)
                    {
                        short max = set1.GetLast();
                        set1.RemoveLast();
                        set2.Enqueue(max);
                    }
                }
                else if (command == "FIND")
                {
                    if (totalSoFar % 2 == 0)
                    {
                        sum  = 0;
                        sum += set1.GetLast() + set2.Peek();
                        sum  = sum / 2;
                        result.AppendLine(sum.ToString());
                    }
                    else if (totalSoFar % 2 == 1)
                    {
                        result.AppendLine(set2.Peek().ToString());
                    }
                }
                input = Console.ReadLine();
            }
            Console.WriteLine(result);
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: Kassomats/TelerikAcademy
        static void Main(string[] args)
        {
            Dictionary <string, OrderedSet <Prod> > playersByTypes = new Dictionary <string, OrderedSet <Prod> >();

            Dictionary <string, Prod> playersByName = new Dictionary <string, Prod>();

            OrderedBag <Prod> playersByPrice = new OrderedBag <Prod>();
            StringBuilder     result         = new StringBuilder();

            string[] command = Console.ReadLine().Split();

            string name  = string.Empty;
            double price = 0;
            string type  = string.Empty;

            while (command[0] != "end")
            {
                switch (command[0])
                {
                case "add":
                    name  = command[1];
                    price = double.Parse(command[2]);
                    type  = command[3];

                    Prod toAdd = new Prod(name, price, type);

                    if (playersByName.ContainsKey(name))
                    {
                        result.AppendLine($"Error: Product {name} already exists");
                        break;
                    }
                    playersByPrice.Add(toAdd);
                    playersByName.Add(name, toAdd);
                    result.AppendLine($"Ok: Product {name} added successfully");

                    if (playersByTypes.ContainsKey(type))
                    {
                        if (playersByTypes[type].Count >= 10)
                        {
                            var lastPlayer = playersByTypes[type][9];

                            if (lastPlayer.CompareTo(toAdd) > 0)
                            {
                                playersByTypes[type].RemoveLast();
                                playersByTypes[type].Add(toAdd);
                            }
                        }
                        else
                        {
                            playersByTypes[type].Add(toAdd);
                        }
                    }
                    else
                    {
                        playersByTypes.Add(type, new OrderedSet <Prod>());
                        playersByTypes[type].Add(toAdd);
                    }

                    break;

                case "filter":

                    if (command[2] == "type")
                    {
                        if (playersByTypes.ContainsKey(command[3]))
                        {
                            result.Append("Ok: ");
                            foreach (var unit in playersByTypes[command[3]])
                            {
                                result.Append(unit.Name);
                                result.Append($"({unit.Price}), ");
                            }
                            if (playersByTypes[command[3]].Count > 0)
                            {
                                result.Length -= 2;
                            }

                            result.AppendLine();
                        }
                        else if (!playersByTypes.ContainsKey(command[3]))
                        {
                            result.AppendLine($"Error: Type {command[3]} does not exists");
                        }
                    }
                    else if (command.Count() == 7)     //from - to
                    {
                        bool   changed = false;
                        int    count   = 0;
                        double from    = double.Parse(command[4]);
                        double to      = double.Parse(command[6]);
                        result.Append("Ok: ");
                        foreach (var item in playersByPrice)
                        {
                            if (count == 10)
                            {
                                break;
                            }
                            if (item.Price >= from && item.Price <= to)
                            {
                                result.Append(item.Name);
                                result.Append($"({item.Price}), ");
                                count++;
                                changed = true;
                            }
                        }
                        if (changed)
                        {
                            result.Length -= 2;
                        }

                        result.AppendLine();
                    }
                    else if (command[3] == "from")   //from
                    {
                        bool changed = false;

                        int    count = 0;
                        double from  = double.Parse(command[4]);
                        result.Append("Ok: ");
                        foreach (var item in playersByPrice)
                        {
                            if (count == 10)
                            {
                                break;
                            }
                            if (item.Price >= from)
                            {
                                changed = true;
                                result.Append(item.Name);
                                result.Append($"({item.Price}), ");
                                count++;
                            }
                        }
                        if (changed)
                        {
                            result.Length -= 2;
                        }

                        result.AppendLine();
                    }
                    else if (command[3] == "to")     //to
                    {
                        bool changed = false;

                        int    count = 0;
                        double to    = double.Parse(command[4]);
                        result.Append("Ok: ");
                        foreach (var item in playersByPrice)
                        {
                            if (count == 10)
                            {
                                break;
                            }
                            if (item.Price <= to)
                            {
                                changed = true;
                                result.Append(item.Name);
                                result.Append($"({item.Price}), ");
                                count++;
                            }
                        }
                        if (changed)
                        {
                            result.Length -= 2;
                        }
                        result.AppendLine();
                    }

                    break;
                }

                command = Console.ReadLine().Split();
            }

            Console.Write(result.ToString());
        }
コード例 #44
0
        public void FindPath(object s)
        {
            // Stopwatch sw = new Stopwatch();
            //sw.Start();

            byte[,] mGrid = (byte[, ])s;


            bool stop       = false;
            int  maxCounter = 0;

            sbyte[,] direction = null;

            if (useDiagonals)
            {
                direction = new sbyte[8, 2] {
                    { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 }, { 1, -1 }, { 1, 1 }, { -1, 1 }, { -1, -1 }
                };
            }
            else
            {
                direction = new sbyte[4, 2] {
                    { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 }
                };
            }


            ushort mGridX = (ushort)(mGrid.GetUpperBound(0) + 1);

            ushort mGridY = (ushort)(mGrid.GetUpperBound(1) + 1);

            ushort mGridXMinus1 = (ushort)(mGridX - 1);

            ushort mGridYLog2 = (ushort)Mathf.Log(mGridY, 2);

            ushort currentX = 0;
            ushort currentY = 0;


            node[]           mCalcGrid = new node[mGridX * mGridY];
            OrderedBag <int> open      = new OrderedBag <int>(new ComparePFNodeMatrix(mCalcGrid));


            int current     = (startY << mGridYLog2) + startX;
            int endLocation = (endY << mGridYLog2) + endX;

            mCalcGrid[current].g = 0;
            mCalcGrid[current].f = 2;

            mCalcGrid[current].pX = (ushort)startX;
            mCalcGrid[current].pY = (ushort)startY;

            mCalcGrid[current].status = openNode;

            int    newCurrent  = 0;
            ushort newCurrentX = 0;
            ushort newCurrentY = 0;
            int    newG        = 0;
            int    newH        = 0;

            open.Add(current);

            while (open.Count > 0 && !stop)
            {
                current = open.GetFirst();

                open.RemoveFirst();
                if (mCalcGrid[current].status == closedNode)
                {
                    continue;
                }
                currentX = (ushort)(current & mGridXMinus1);
                currentY = (ushort)(current >> mGridYLog2);

                if (maxCounter > maxSearch)
                {                //Failed to find!
                    stop = true; //UnityEngine.Debug.Log("stopped");
                }

                if (current == endLocation)
                {                                           //End found!
                    mCalcGrid[current].status = closedNode; //UnityEngine.Debug.Log("found");
                    pathFound = true;
                    break;
                }

                for (int i = 0; i < (useDiagonals ? 8 : 4); i++)
                {
                    newCurrentX = (ushort)(currentX + direction[i, 0]);
                    newCurrentY = (ushort)(currentY + direction[i, 1]);
                    newCurrent  = (newCurrentY << mGridYLog2) + newCurrentX;

                    if (newCurrentX >= mGridX || newCurrentY >= mGridY)
                    {
                        continue;
                    }

                    if (mGrid[newCurrentX, newCurrentY] == 0)
                    {
                        continue;                                       //if node is not walkable
                    }
                    if (heavyDiagonals && i > 3)
                    {
                        newG = mCalcGrid[current].g + (int)(mGrid[newCurrentX, newCurrentY] * 2.41);
                    }
                    else
                    {
                        newG = mCalcGrid[current].g + mGrid[newCurrentX, newCurrentY];
                    }

                    //is it open or closed?

                    if (mCalcGrid[newCurrent].status == openNode || mCalcGrid[newCurrent].status == closedNode)
                    {
                        if (mCalcGrid[newCurrent].g <= newG)
                        {
                            continue;
                        }
                    }

                    mCalcGrid[newCurrent].pX = currentX;
                    mCalcGrid[newCurrent].pY = currentY;
                    mCalcGrid[newCurrent].g  = newG;

                    switch (formula)
                    {
                    default:
                    case HeuristicFormula.Manhattan:
                        newH = mHEstimate * (Mathf.Abs(newCurrentX - endX) + Mathf.Abs(newCurrentY - endY));
                        break;

                    case HeuristicFormula.MaxDXDY:
                        newH = mHEstimate * (Mathf.Max(Mathf.Abs(newCurrentX - endX), Mathf.Abs(newCurrentY - endY)));
                        break;

                    case HeuristicFormula.DiagonalShortcut:
                        int h_diagonal = Mathf.Min(Mathf.Abs(newCurrentX - endX), Mathf.Abs(newCurrentY - endY));
                        int h_straight = (Mathf.Abs(newCurrentX - endX) + Mathf.Abs(newCurrentY - endY));
                        newH = (mHEstimate * 2) * h_diagonal + mHEstimate * (h_straight - 2 * h_diagonal);
                        break;

                    case HeuristicFormula.Euclidean:
                        newH = (int)(mHEstimate * Mathf.Sqrt(Mathf.Pow((newCurrentX - endX), 2) + Mathf.Pow((newCurrentY - endY), 2)));
                        // type could be Y?
                        break;

                    case HeuristicFormula.EuclideanNoSQR:
                        newH = (int)(mHEstimate * (Mathf.Pow((newCurrentX - endX), 2) + Mathf.Pow((newCurrentY - endY), 2)));
                        break;
                    }

                    if (tieBreaker)
                    {
                        int dx1   = currentX - endX;
                        int dy1   = currentY - endY;
                        int dx2   = startX - endX;
                        int dy2   = startY - endY;
                        int cross = Mathf.Abs(dx1 * dy2 - dx2 * dy1);
                        newH = (int)(newH + cross * 0.001);
                    }

                    mCalcGrid[newCurrent].f = newG + newH;
                    open.Add(newCurrent);
                    mCalcGrid[newCurrent].status = openNode;
                }
                maxCounter++;
                mCalcGrid[current].status = closedNode;
            }

            if (pathFound)
            {
                //UnityEngine.Debug.Log(maxCounter);
                path = new List <Point>();
                Point pos       = new Point(currentX, currentY);
                int   startNode = (startY << mGridYLog2) + startX;

                int xp = currentX;
                int yp = currentY;

                int test = 0;
                while (current != startNode)
                {
                    pos = new Point(xp, yp);
                    // pos = (bottomLeft + Vector2.right * xp * nodeSize + Vector2.up * yp * nodeSize); wafawefawef
                    //path.Add(grid[pos.x,pos.y].position);
                    path.Add(pos);

                    xp      = mCalcGrid[current].pX;
                    yp      = mCalcGrid[current].pY;
                    current = (mCalcGrid[current].pY << mGridYLog2) + mCalcGrid[current].pX;
                    test++;
                    if (test > 3000)
                    {
                        //UnityEngine.Debug.Log("broke");
                        break;
                    }
                }

                path.Reverse();
            }
            //UnityEngine.Debug.Log(path.Count + " finish");

            //sw.Stop();
            //UnityEngine.Debug.Log(sw.Elapsed.TotalMilliseconds);

            done = true;
            _doneEvent.Set();
        }
コード例 #45
0
 public void Enqueue(T element)
 {
     queue.Add(element);
 }
コード例 #46
0
        static void Main()
        {
            var n = int.Parse(Console.ReadLine());

            var points = new SweepPoint[n * 2];

            for (int i = 0; i < n; ++i)
            {
                var strs = Console.ReadLine().Split(' ');
                var l    = int.Parse(strs[0]);
                var r    = int.Parse(strs[1]);
                var h    = int.Parse(strs[2]);

                points[i * 2] = new SweepPoint
                {
                    X      = l,
                    Height = h,
                    IsLeft = true
                };
                points[i * 2 + 1] = new SweepPoint
                {
                    X      = r,
                    Height = h,
                    IsLeft = false
                };
            }

            Array.Sort(points, (x, y) => x.X - y.X);

            var result = new List <Point>();

            var heights = new OrderedBag <int>();

            heights.Add(0);

            foreach (var p in points)
            {
                if (p.IsLeft)
                {
                    heights.Add(p.Height);
                }
                else
                {
                    heights.Remove(p.Height);
                }

                var newPoint = new Point {
                    X = p.X, Y = heights.GetLast()
                };
                result.Add(newPoint);
            }

            var lastHeight = 0;

            for (int i = 0; i < result.Count; ++i)
            {
                var p = result[i];

                if (p.Y == lastHeight)
                {
                    continue;
                }

                if (i + 1 < result.Count && p.X == result[i + 1].X)
                {
                    continue;
                }

                Console.WriteLine("{0} {1}", p.X, p.Y);
                lastHeight = p.Y;
            }
        }
コード例 #47
0
 public void Enqueue(T element)
 {
     bag.Add(element);
 }
コード例 #48
0
    static void Main()
    {
        Console.Write("Bag of Integers: ");
        var bagOfInts = new Bag <int>();

        bagOfInts.Add(3);
        bagOfInts.Add(5);
        bagOfInts.Add(5);
        bagOfInts.Add(5);
        bagOfInts.Add(10);
        bagOfInts.Add(20);
        bagOfInts.Add(20);
        bagOfInts.Remove(5);
        bagOfInts.RemoveAllCopies(20);
        bagOfInts.UnionWith(new Bag <int>()
        {
            3, 3, 4, 4, 5, 5
        });
        Console.WriteLine(bagOfInts);

        Console.Write("OrderedBag of Integers: ");
        var orderedBagOfInts = new OrderedBag <int>();

        orderedBagOfInts.Add(3);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(5);
        orderedBagOfInts.Add(10);
        orderedBagOfInts.Add(20);
        orderedBagOfInts.Add(20);
        orderedBagOfInts.Remove(5);
        orderedBagOfInts.RemoveAllCopies(20);
        orderedBagOfInts.UnionWith(new OrderedBag <int>()
        {
            3, 3, 4, 4, 5, 5
        });
        Console.WriteLine(orderedBagOfInts);
        Console.WriteLine("Sub-range [5...10]: " +
                          orderedBagOfInts.Range(5, true, 10, true));

        Console.Write("Set of Integers: ");
        var setOfInts = new Set <int>();

        setOfInts.Add(3);
        setOfInts.Add(5);
        setOfInts.Add(5);
        setOfInts.Add(5);
        setOfInts.Add(10);
        setOfInts.Add(20);
        setOfInts.Add(20);
        setOfInts.Remove(5);
        setOfInts.UnionWith(new Set <int>()
        {
            3, 4, 5
        });
        Console.WriteLine(setOfInts);

        Console.Write("OrderedSet of Integers: ");
        var orderedSetOfInts = new OrderedSet <int>();

        orderedSetOfInts.Add(3);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(5);
        orderedSetOfInts.Add(10);
        orderedSetOfInts.Add(20);
        orderedSetOfInts.Add(20);
        orderedSetOfInts.Remove(5);
        orderedSetOfInts.UnionWith(new OrderedSet <int>()
        {
            3, 4, 5
        });
        Console.WriteLine(orderedSetOfInts);
        Console.WriteLine("Sub-range [5...20): " +
                          orderedSetOfInts.Range(5, true, 20, false));

        Console.Write("MultiDictionary<string,int>: ");
        var studentGrades = new MultiDictionary <string, int>(true);

        studentGrades.Add("Peter", 3);
        studentGrades.Add("Peter", 4);
        studentGrades.Add("Peter", 4);
        studentGrades.Add("Stanka", 6);
        studentGrades.Add("Stanka", 5);
        studentGrades.Add("Stanka", 6);
        studentGrades.Add("Tanya", 6);
        studentGrades.Add("Tanya", 4);
        Console.WriteLine(studentGrades);

        Console.WriteLine("OrderedMultiDictionary<string,int>:");
        var distancesFromSofia = new OrderedMultiDictionary <int, string>(true);

        distancesFromSofia.Add(149, "Plovdiv");
        distancesFromSofia.Add(505, "Varna");
        distancesFromSofia.Add(394, "Bourgas");
        distancesFromSofia.Add(310, "Rousse");
        distancesFromSofia.Add(163, "Pleven");
        distancesFromSofia.Add(163, "Troyan");
        foreach (var distanceTowns in distancesFromSofia)
        {
            Console.WriteLine("\t" + distanceTowns);
        }

        Console.Write("Deque<string>: ");
        var people = new Deque <string>();

        people.AddToBack("Kiro");
        people.AddToBack("Maria");
        people.AddToFront("Steve");
        people.AddManyToBack(new string[] { "Ivan", "Veronika" });
        Console.WriteLine(people);

        Console.Write("BigList<int>: ");
        var ints = new BigList <int>();

        // var ints = new List<int>();
        for (int i = 0; i < 1000000; i++)
        {
            ints.Add(i);
        }
        for (int i = 0; i < 50000; i++)
        {
            ints.Insert(i, i);
        }
        Console.WriteLine(ints.Count);
    }
コード例 #49
0
 public void Add(T element)
 {
     byInsertionOrder.AddLast(element);
     byValue.Add(byInsertionOrder.Last);
     byValueReversed.Add(byInsertionOrder.Last);
 }
コード例 #50
0
        public static void Main(string[] args)
        {
            Dictionary <string, Unit> units = new Dictionary <string, Unit>();

            OrderedBag <Unit> bagOfUnits = new OrderedBag <Unit>();

            Dictionary <string, OrderedBag <Unit> > unitsByUnittype = new Dictionary <string, OrderedBag <Unit> >();

            string command;

            while ((command = Console.ReadLine()) != "end")
            {
                string[] subcommand = command.Split();

                switch (subcommand[0])
                {
                case "add":
                {
                    string name   = subcommand[1];
                    string type   = subcommand[2];
                    int    attack = int.Parse(subcommand[3]);

                    Unit unit = new Unit();
                    unit.Name   = name;
                    unit.Type   = type;
                    unit.Attack = attack;

                    if (units.ContainsKey(name))
                    {
                        Console.WriteLine("FAIL: {0} already exists!", name);
                    }
                    else
                    {
                        units.Add(name, unit);
                        bagOfUnits.Add(unit);

                        if (unitsByUnittype.ContainsKey(type))
                        {
                            unitsByUnittype[type].Add(unit);
                        }
                        else
                        {
                            unitsByUnittype.Add(type, new OrderedBag <Unit>()
                                {
                                    unit
                                });
                        }

                        Console.WriteLine("SUCCESS: {0} added!", name);
                    }
                    break;
                }

                case "remove":
                {
                    string name = subcommand[1];
                    if (units.ContainsKey(name))
                    {
                        var unitToDelete = units[name];
                        units.Remove(name);
                        bagOfUnits.Remove(unitToDelete);
                        unitsByUnittype[unitToDelete.Type].Remove(unitsByUnittype[unitToDelete.Type].First(x => x.Name == name));

                        Console.WriteLine("SUCCESS: {0} removed!", name);
                    }
                    else
                    {
                        Console.WriteLine("FAIL: {0} could not be found!", name);
                    }
                    break;
                }

                case "find":
                {
                    string        type    = subcommand[1];
                    StringBuilder builder = new StringBuilder();
                    builder.Append("RESULT: ");

                    if (unitsByUnittype.ContainsKey(type))
                    {
                        builder.Append(string.Join("", unitsByUnittype[type].Take(10)));
                    }

                    if (builder[builder.Length - 2] == ',')
                    {
                        builder.Remove(builder.Length - 2, 2);
                    }
                    Console.WriteLine(builder.ToString());
                    break;
                }

                case "power":
                {
                    int           numberOfUnits = int.Parse(subcommand[1]);
                    StringBuilder builder       = new StringBuilder();
                    builder.Append("RESULT: ");

                    builder.Append(string.Join("", bagOfUnits.Take(numberOfUnits)));

                    if (builder[builder.Length - 2] == ',')
                    {
                        builder.Remove(builder.Length - 2, 2);
                    }
                    Console.WriteLine(builder.ToString());
                    break;
                }
                }
            }
        }
コード例 #51
0
    static ICollection <Path> GetNeighbourhood()
    {
        OrderedBag <Path> neighbourhood = new OrderedBag <Path>();

        neighbourhood.Add(new Path(new House("1"), new House("2"), 2));
        neighbourhood.Add(new Path(new House("1"), new House("3"), 22));
        neighbourhood.Add(new Path(new House("1"), new House("10"), 7));
        neighbourhood.Add(new Path(new House("2"), new House("10"), 12));
        neighbourhood.Add(new Path(new House("2"), new House("9"), 4));
        neighbourhood.Add(new Path(new House("2"), new House("3"), 1));
        neighbourhood.Add(new Path(new House("3"), new House("5"), 7));
        neighbourhood.Add(new Path(new House("4"), new House("3"), 9));
        neighbourhood.Add(new Path(new House("10"), new House("8"), 12));
        neighbourhood.Add(new Path(new House("8"), new House("6"), 17));
        neighbourhood.Add(new Path(new House("8"), new House("7"), 8));
        neighbourhood.Add(new Path(new House("5"), new House("7"), 9));
        neighbourhood.Add(new Path(new House("6"), new House("5"), 18));
        neighbourhood.Add(new Path(new House("4"), new House("5"), 7));
        neighbourhood.Add(new Path(new House("4"), new House("6"), 13));
        neighbourhood.Add(new Path(new House("4"), new House("9"), 4));
        neighbourhood.Add(new Path(new House("8"), new House("9"), 5));
        neighbourhood.Add(new Path(new House("4"), new House("8"), 6));

        //neighbourhood.Add(new Path(new House("1"), new House("2"), 1));
        //neighbourhood.Add(new Path(new House("4"), new House("1"), 2));
        //neighbourhood.Add(new Path(new House("2"), new House("3"), 3));
        //neighbourhood.Add(new Path(new House("2"), new House("5"), 13));
        //neighbourhood.Add(new Path(new House("4"), new House("3"), 4));
        //neighbourhood.Add(new Path(new House("3"), new House("6"), 3));
        //neighbourhood.Add(new Path(new House("4"), new House("6"), 16));
        //neighbourhood.Add(new Path(new House("4"), new House("7"), 14));
        //neighbourhood.Add(new Path(new House("5"), new House("6"), 12));
        //neighbourhood.Add(new Path(new House("5"), new House("8"), 1));
        //neighbourhood.Add(new Path(new House("5"), new House("9"), 13));
        //neighbourhood.Add(new Path(new House("6"), new House("7"), 1));
        //neighbourhood.Add(new Path(new House("6"), new House("9"), 1));

        return(neighbourhood);
    }
コード例 #52
0
 public void Enqueue(T element)
 {
     multiset.Add(element);
 }
コード例 #53
0
        static void Main()
        {
            int nodesCount = int.Parse(Console.ReadLine().Split(' ')[1]);

            string[] pathTokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int      startNode  = int.Parse(pathTokens[1]);
            int      endNode    = int.Parse(pathTokens[3]);

            int edgesCount = int.Parse(Console.ReadLine().Split(' ')[1]);

            graph = new Dictionary <int, List <Edge> >();

            ReadGraph(edgesCount);

            percentages            = Enumerable.Repeat <double>(-1, graph.Count).ToArray();
            percentages[startNode] = 100;

            bool[] visited = new bool[graph.Count];
            visited[startNode] = true;

            previous            = new int[graph.Count];
            previous[startNode] = -1;

            //Djikstra's algorithm

            var queue = new OrderedBag <int>(Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));

            queue.Add(startNode);

            while (queue.Any())
            {
                int nodeWithMaxPercentage = queue.RemoveFirst();

                if (percentages[nodeWithMaxPercentage] == -1)
                {
                    break; //reached a node with no path further
                }

                foreach (Edge edge in graph[nodeWithMaxPercentage])
                {
                    var otherNode = edge.FirstNode == nodeWithMaxPercentage
                        ? edge.SecondNode
                        : edge.FirstNode;

                    if (!visited[otherNode])
                    {
                        visited[otherNode] = true;
                        queue.Add(otherNode);
                    }

                    double newPercentage = percentages[nodeWithMaxPercentage] / 100 * edge.Cost;

                    if (percentages[otherNode] < newPercentage)
                    {
                        percentages[otherNode] = newPercentage;
                        previous[otherNode]    = nodeWithMaxPercentage;

                        //have yo sort again because percentages has changed
                        queue = new OrderedBag <int>(
                            queue,
                            Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));
                    }
                }
            }

            PrintMostReliablePath(endNode);
        }
コード例 #54
0
        private void astar(long x, long y)
        {
            double bound = md.n + md.m;
            OrderedBag <KeyValuePair <long, Point> > pq  = new OrderedBag <KeyValuePair <long, Point> >(new cmp());
            OrderedBag <KeyValuePair <long, Point> > pq2 = new OrderedBag <KeyValuePair <long, Point> >(new cmp());

            V2 = new System.Windows.Vector(md.edx - x, md.edy - y);
            V1 = new System.Windows.Vector(1, 0);
            //FastPriorityQueue<node> pq = new FastPriorityQueue<node>(md.n*md.m/10);
            //PriorityQueue pq = new PriorityQueue((IComparer)new cmp());
            pq.Add(new KeyValuePair <long, Point>(G[x, y] + H(new Point((int)x, (int)y)), new Point((int)x, (int)y)));
            //pq.Enqueue(new KeyValuePair<long,Point>(G[x, y] + H(new Point(x, y)), new Point(x, y))));
            G[x, y]   = 1;
            vis[x, y] = true;
            KeyValuePair <long, Point> kvp;

            while (pq.Count != 0)
            {
                if (pq.Count != 0)
                {
                    kvp = pq.RemoveFirst();
                }
                else
                {
                    kvp = pq2.RemoveFirst();
                }
                x = kvp.Value.X;
                y = kvp.Value.Y;
                md.Que.Enqueue(new DrawTask((int)x * md.pW, (int)y * md.pH, md.pW, md.pH, Color.Green));
                Thread.Sleep(md.delay);
                for (long i = 0; i < 4; i++)
                {
                    long g   = x + dir[i, 0];
                    long h   = y + dir[i, 1];
                    long now = kvp.Key;

                    if (g >= 0 && h >= 0 && g < md.n && h < md.m)
                    {
                        if (!vis[g, h] && md.myMaze.maze[g, h] == 0)
                        {
                            G[g, h] = G[x, y] + 1;
                            if (g == md.edx && h == md.edy)
                            {
                                parent[g, h] = new KeyValuePair <long, long>(x, y);
                                md.Que.Enqueue(new DrawTask((int)x * md.pW, (int)y * md.pH, md.pW, md.pH, Color.Green));
                                Thread.Sleep(md.delay);
                                markPath((int)g, (int)h);
                                return;
                            }
                            V1 = new System.Windows.Vector(g - x, h - y);
                            V2 = new System.Windows.Vector(md.edx - x, md.edy - y);
                            long here = G[g, h] + H(new Point((int)g, (int)h));
                            vis[g, h]    = true;
                            parent[g, h] = new KeyValuePair <long, long>(x, y);
                            pq.Add(new KeyValuePair <long, Point>(here, new Point((int)g, (int)h)));
                            if (pq.Count > bound)
                            {
                                pq2.Add(pq.RemoveLast());
                            }
                        }
                    }
                }
            }
        }
コード例 #55
0
        private static void Diikstra(int startNode)
        {
            var maxKey    = graph.Length;
            var distances = new TimeSpan[maxKey];
            var prev      = new int[maxKey];

            for (int i = 0; i < distances.Length; i++)
            {
                distances[i] = TimeSpan.MaxValue;
            }
            distances[startNode] = new TimeSpan(0, 0, 0);
            var queue = new OrderedBag <int>(Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));
            var end   = -1;

            queue.Add(startNode);

            while (queue.Count > 0)
            {
                var minEdge = queue.RemoveFirst();

                if (exitRooms.Contains(minEdge))
                {
                    end = minEdge;
                    break;
                }

                foreach (var child in graph[minEdge])
                {
                    var actualChild       = minEdge == child.First ? child.Second : child.First;
                    var actualChildWeight = child.Time + distances[minEdge];
                    if (distances[actualChild] == TimeSpan.MaxValue)
                    {
                        queue.Add(actualChild);
                    }

                    if (distances[actualChild] > actualChildWeight)
                    {
                        distances[actualChild] = actualChildWeight;
                        prev[actualChild]      = minEdge;
                        queue = new OrderedBag <int>(queue, Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));
                    }
                }
            }

            if (end != -1)
            {
                var curTime = distances[end];
                if (curTime <= time)
                {
                    Console.WriteLine($"Safe {startNode} ({curTime})");
                }
                else
                {
                    Console.WriteLine($"Unsafe {startNode} ({curTime})");
                }
            }
            else
            {
                Console.WriteLine($"Unreachable {startNode} (N/A)");
            }
        }
コード例 #56
0
    public void AddInvader(Invader invader)
    {
        var node = byInsertion.AddLast(invader);

        byPriority.Add(node);
    }
コード例 #57
0
ファイル: Program.cs プロジェクト: trinityimma/TelerikAcademy
    // Almost the same as Programming/5.DataStructuresAndAlgorithms/AlgoAcademy/4.DataStructures/2.Zadachi/Program.cs
    static void Main()
    {
#if DEBUG
        Console.SetIn(new System.IO.StreamReader("../../input.txt"));
#endif

        var date = DateTime.Now;

        var tasks = new OrderedBag <Tuple <string, int> >((task1, task2) =>
        {
            int compared = 0;

            compared = task1.Item2.CompareTo(task2.Item2);
            if (compared != 0)
            {
                return(compared);
            }

            compared = task1.Item1.CompareTo(task2.Item1);
            if (compared != 0)
            {
                return(compared);
            }

            return(compared);
        });

        var output = new StringBuilder();

        var separator = new char[] { ' ' };

        foreach (int i in Enumerable.Range(0, int.Parse(Console.ReadLine())))
        {
            string line = Console.ReadLine();

            if (line == "Solve")
            {
                if (tasks.Count == 0)
                {
                    output.AppendLine("Rest");
                }

                else
                {
                    output.AppendLine(tasks.RemoveFirst().Item1);
                }
            }

            else
            {
                var match = line.Split(separator, 3);

                tasks.Add(new Tuple <string, int>(match[2], int.Parse(match[1])));
            }
        }

        Console.Write(output);

#if DEBUG
        Console.WriteLine(DateTime.Now - date);
#endif
    }
コード例 #58
0
 private static void AddNumber(int num)
 {
     numbers.Add(num);
 }
コード例 #59
0
 public void AddObjectToQueue(PlannedEvent plannedEvent)
 {
     plannedEvent.NextStateTick = CurrentTick + DayNightCycle.HalfDayLength - (int)((DayNightCycle.HalfDayLength / 10) * Game.Random.NextDouble());
     _queue.Add(plannedEvent);
 }
コード例 #60
0
        static void Main(string[] args)
        {
            // var queue = new OrderedBag<int>(Comparer<int>.Create((f, s) => s - f));
            var e = int.Parse(Console.ReadLine() ?? string.Empty);

            _edgesByNode = ReadGraph(e);
            var start = int.Parse(Console.ReadLine() ?? string.Empty);
            var end   = int.Parse(Console.ReadLine() ?? string.Empty);

            var maxNode = _edgesByNode.Keys.Max();

            var distances = new int[maxNode + 1];

            for (int i = 0; i < distances.Length; i++) // // Framework C# code
            {
                distances[i] = int.MaxValue;
            }


            distances[start] = 0;

            var prev = new int[maxNode + 1];

            prev[start] = -1;

            var queue = new OrderedBag <int>(
                Comparer <int> .Create((f, s) => distances[f] - distances[s]))
            {
                start
            };

            while (queue.Count > 0)
            {
                var minNode  = queue.RemoveFirst();
                var children = _edgesByNode[minNode];

                if (minNode == end || distances[minNode] == int.MaxValue)
                {
                    break;
                }

                foreach (var child in children)
                {
                    var childNode = child.First == minNode ? child.Second : child.First;

                    if (distances[childNode] == int.MaxValue)
                    {
                        queue.Add(childNode);
                    }

                    var newDistance = child.Weight + distances[minNode];

                    if (newDistance >= distances[childNode])
                    {
                        continue;
                    }
                    distances[childNode] = newDistance;
                    prev[childNode]      = minNode;
                    queue = new OrderedBag <int>(queue, Comparer <int> .Create((f, s) => distances[f] - distances[s]));
                }
            }

            if (distances[end] == int.MaxValue)
            {
                Console.WriteLine("There is no such path.");
                return;
            }

            Console.WriteLine(distances[end]);

            var path = new Stack <int>();

            var node = end;

            while (node != -1)
            {
                path.Push(node);
                node = prev[node];
            }

            Console.WriteLine(string.Join(" ", path));
        }