示例#1
0
        /// <summary>
        /// Force update the entropy of this chunk.
        /// </summary>
        void UpdateEntropy()
        {
            var sumOfWeight          = Compatibles.Sum(pattern => pattern.Weight);
            var sumOfWeightLogWeight = Compatibles.Sum(pattern => pattern.Weight * Mathf.Log(pattern.Weight));

            Entropy = Mathf.Log(sumOfWeight) - sumOfWeightLogWeight / sumOfWeight;
        }
示例#2
0
        public void BloomFilterTest()
        {
            Assert.Inconclusive("Not Implemented");
            // تعداد پسوردها - ثابت. عوض نکنید.
            int pwdCount = 1_000_000;

            // اندازه مناسب را خودتون انتخاب کنید
            int filterSize = (5 * pwdCount);

            // تعداد توابع را هم خودتان تنظیم کنید
            int hashFnCount = 3;

            Q3BloomFilter    filter    = new Q3BloomFilter(filterSize, hashFnCount);
            HashSet <string> passwords = new HashSet <string>();

            foreach (string pwd in RandomStringGenerator(pwdCount, 0))
            {
                // پسورد را به فیلتر اضافه کن
                filter.Add(pwd);

                // پسوردها را در یک دیکشنری هم ذخیره کن که بتوانیم
                // false positive rate
                // را حساب کنیم
                passwords.Add(pwd);
            }

            // تمام پسوردهای اضافه شده باید حتما جواب مثبت بدهند
            foreach (string pwd in passwords)
            {
                Assert.IsTrue(filter.Test(pwd));
            }

            double falsePositive = 0;

            foreach (string pwd in RandomStringGenerator(pwdCount, 1))
            {
                bool filterAnswer = filter.Test(pwd);
                bool trueAnswer   = passwords.Contains(pwd);

                // اگر فیلتر بگه توی لیست نیست، ولی واقعا باشه که کلا اشتباه شده
                Assert.IsFalse(!filterAnswer && trueAnswer);

                // اگر فیلتر بگه توی لیست هست ولی واقعا نباشه میشه falsePositive
                if (!trueAnswer && filterAnswer)
                {
                    falsePositive++;
                }
            }

            double falsePositiveRatio = falsePositive / pwdCount;
            double storageRatio       = ((double)filterSize) / (passwords.Sum(x => x.Length * 8));

            Console.WriteLine($"False Positive Ratio: {falsePositiveRatio}");
            Console.WriteLine($"Bloom Filter Size =  {filterSize / 8 / 1024}K");
            Console.WriteLine($"Password File Size =  {passwords.Sum(x => x.Length) / 1024}K");
            Console.WriteLine($"Storage Ratio =  {storageRatio}");

            Assert.IsTrue(falsePositiveRatio < 0.1);
            Assert.IsTrue(storageRatio < 0.05);
        }
示例#3
0
        private void logResults(IList <NeatGenome> genomeList)
        {
            var maxFitness    = genomeList.Max(g => g.EvaluationInfo.Fitness);
            var maxAltFitness = genomeList.Max(g => g.EvaluationInfo.AlternativeFitness);

            // Write the results to file.
            using (TextWriter writer = new StreamWriter(AGGREGATE_RESULTS_FILE, true))
            {
                Console.WriteLine("Gen {0}: {1} ({2}) Total: {3}", _generations,
                                  maxFitness,
                                  maxAltFitness,
                                  Found.Count);

                Console.WriteLine("{0},{1},{2},{3},{4},{5},{6}", _generations,
                                  maxFitness,
                                  maxAltFitness,
                                  genomeList.Average(g => g.EvaluationInfo.Fitness),
                                  genomeList.Average(g => g.EvaluationInfo.AlternativeFitness),
                                  Found.Sum(s => Program.Accounts[s].Accounts),
                                  Found.Count
                                  );
                writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", _generations,
                                 maxFitness,
                                 maxAltFitness,
                                 genomeList.Average(g => g.EvaluationInfo.Fitness),
                                 genomeList.Average(g => g.EvaluationInfo.AlternativeFitness),
                                 Found.Sum(s => Program.Accounts[s].Accounts),
                                 Found.Count);
            }
        }
示例#4
0
 /// <summary>
 /// Adds the specified item to the station.
 /// </summary>
 /// <param name="item">The item to add.</param>
 /// <returns><code>true</code> if the item was added successfully, <code>false</code> otherwise.</returns>
 public bool Add(ItemBundle item)
 {
     if (CapacityInUse + item.BundleWeight <= Capacity)
     {
         // Add the bundle
         if (Instance.SettingConfig.VisualizationAttached)
         {
             lock (_syncRoot)
                 _itemBundles.Add(item);
         }
         else
         {
             _itemBundles.Add(item);
         }
         // Keep track of capacity
         CapacityInUse = _itemBundles.Sum(b => b.BundleWeight);
         // Remove the bundle from the reservation list
         _registeredBundles.Remove(item);
         CapacityReserved = _registeredBundles.Sum(b => b.BundleWeight);
         // Notify instance about the allocation
         Instance.NotifyBundleAllocated(this, item);
         // Reset down-time
         _statDepletionTime = double.PositiveInfinity;
         // Return success
         return(true);
     }
     else
     {
         // Return fail
         return(false);
     }
 }
示例#5
0
        /// <summary>
        /// Cria uma nova instância de <see cref="Operacao"/> a partir dos dados do modelo de domínio.
        /// </summary>
        /// <param name="operacao">Entidade de domínio.</param>
        public Operacao(IOperacao operacao)
        {
            _operacao = operacao;

            var parcelasDaOperacao = new HashSet <Parcela>(
                operacao.Parcelas
                .Where(parcela => parcela.EntidadeValida)
                .Select(parcela => new Parcela(this)
            {
                DataDeVencimento = parcela.DataDeVencimento,
                Prazo            = parcela.Prazo,
                Valor            = parcela.Valor,
                ValorDeJuros     = parcela.ValorDeJuros,
                ValorDeIof       = parcela.ValorApuradoPorImposto <IIof>(),
                ValorDePis       = parcela.ValorApuradoPorImposto <IPis>(),
                ValorDeCofins    = parcela.ValorApuradoPorImposto <ICofins>()
            }));

            DataDaOperacao = operacao.DataDaOperacao;
            TaxaDeIof      = operacao.TaxaDeIof;
            TaxaDeJuros    = operacao.TaxaDeJuros;
            TipoDeOperacao = (byte)operacao.TipoDeOperacao;
            Parcelas       = parcelasDaOperacao;
            Valor          = parcelasDaOperacao.Sum(parcela => parcela.Valor);
            ValorDeJuros   = parcelasDaOperacao.Sum(parcela => parcela.ValorDeJuros);
            ValorDeIof     = parcelasDaOperacao.Sum(parcela => parcela.ValorDeIof);
            ValorDePis     = parcelasDaOperacao.Sum(parcela => parcela.ValorDePis);
            ValorDeCofins  = parcelasDaOperacao.Sum(parcela => parcela.ValorDeCofins);
        }
示例#6
0
        private void ValidateParsedItems(HashSet <IBankovniPolozka> polozky, StatementOverview overview)
        {
            var currentCredit = polozky.Sum(p => p.Castka > 0 ? p.Castka : 0);

            if (overview.CreditSum != currentCredit)
            {
                throw new ApplicationException(
                          $"Invalid total credit (expected {overview.CreditSum}, found {currentCredit}) - {Ucet.Url}");
            }

            var currentDebit = polozky.Sum(p => p.Castka < 0 ? p.Castka : 0);

            if (overview.DebitSum != currentDebit)
            {
                throw new ApplicationException(
                          $"Invalid total debit (expected {overview.DebitSum}, found {currentDebit}) - {Ucet.Url}");
            }

            var currentFinalBalance = overview.OpeningBalance + currentCredit + currentDebit;

            if (overview.FinalBalance != currentFinalBalance)
            {
                throw new ApplicationException(
                          $"Invalid final balance (expected {overview.FinalBalance}, found {currentFinalBalance}) - {Ucet.Url}");
            }
        }
示例#7
0
        public void CanMatchSeasons()
        {
            HashSet <int> seasons    = new HashSet <int>();
            HashSet <int> eventTypes = new HashSet <int>();
            PreOutfit     po         = new PreOutfit();

            Combination c = new Combination();

            c.GarmentA            = new MasterGarment();
            c.GarmentA.EventCode  = 3;
            c.GarmentA.SeasonCode = 15;

            po.Accesory1            = new MasterGarment();
            po.Accesory1.EventCode  = 3;
            po.Accesory1.SeasonCode = 3;

            c.GarmentB            = new MasterGarment();
            c.GarmentB.EventCode  = 1;
            c.GarmentB.SeasonCode = 3;

            po.Combination = c;
            OutfitValidationService.VerifyAndSetSeasonsAndEventTypes(seasons, eventTypes, po);

            Assert.IsTrue(seasons.Sum() == 3, seasons.Sum().ToString());
            Assert.IsTrue(eventTypes.Sum() == 1, eventTypes.Sum().ToString());
        }
示例#8
0
        public static Point CenterPoint(List <Point> points)
        {
            HashSet <Point> hashPoints = new HashSet <Point>(points);
            int             pivotX     = hashPoints.Sum((point) => point.X) / hashPoints.Count;
            int             pivotY     = hashPoints.Sum((point) => point.Y) / hashPoints.Count;

            return(new Point(pivotX, pivotY));
        }
示例#9
0
 /// <summary>
 /// Reserves capacity of this station for the given bundle. The reserved capacity will be maintained when the bundle is allocated.
 /// </summary>
 /// <param name="bundle">The bundle for which capacity shall be reserved.</param>
 internal void RegisterBundle(ItemBundle bundle)
 {
     _registeredBundles.Add(bundle);
     CapacityReserved = _registeredBundles.Sum(b => b.BundleWeight);
     if (CapacityInUse + CapacityReserved > Capacity)
     {
         throw new InvalidOperationException("Cannot reserve more capacity than this station has!");
     }
 }
示例#10
0
        protected override void UpdateRightPane()
        {
            // If we're loading, show it.
            if (isLoading)
            {
                SetRightPaneChild(loadingWidget);
                return;
            }

            var rows = TreeView.Selection.GetSelectedRows();

            if (rows.Length != 0)
            {
                var packageNames = new HashSet <string>();
                var packageRefs  = new List <PackageReference>();
                foreach (var row in rows)
                {
                    TreeIter iter;
                    Model.GetIter(out iter, row);
                    var packageRef = (PackageReference)Model.GetValue(iter, PACKAGE_REF_COLUMN);
                    packageRefs.Add(packageRef);
                    packageNames.Add(packageRef.Name);
                }

                // Are all these packages loaded?
                if (packageNames.All(x => PackageManager.IsLoaded(x)))
                {
                    if (packageNames.Count == 1)
                    {
                        entriesWidget.Packages = packageRefs.ToList();
                        SetRightPaneChild(entriesWidget);
                    }
                    else
                    {
                        SetRightPaneChild(selectOneWidget);
                    }
                }
                else
                {
                    var countUnloaded = packageNames.Sum(x => PackageManager.IsLoaded(x) ? 0 : 1);
                    var sizeUnloaded  = packageNames.Sum(x => PackageManager.IsLoaded(x) ? 0 : PackageManager.GetPackageSize(x));
                    loadPackageWidget.Label = string.Format(
                        "Load in {0} package{1} ({2})",
                        countUnloaded,
                        countUnloaded == 1 ? "" : "s",
                        Util.NumBytesToString(sizeUnloaded)
                        );
                    SetRightPaneChild(loadPackageWidget);
                }
            }
            else
            {
                SetRightPaneChild(noSelectionWidget);
            }
        }
示例#11
0
文件: Pod.cs 项目: xor-lab/RAWSim-O
 /// <summary>
 /// Reserves capacity of this pod for the given bundle. The reserved capacity will be maintained when the bundle is allocated.
 /// </summary>
 /// <param name="bundle">The bundle for which capacity shall be reserved.</param>
 internal void RegisterBundle(ItemBundle bundle)
 {
     _registeredBundles.Add(bundle);
     CapacityReserved = _registeredBundles.Sum(b => b.BundleWeight);
     if (CapacityInUse + CapacityReserved > Capacity)
     {
         throw new InvalidOperationException("Cannot reserve more capacity than this pod has!");
     }
     // Notify the instance about the reservation
     Instance.NotifyBundleRegistered(this, bundle);
 }
示例#12
0
        public void AddRemoveTest()
        {
            var rng = new System.Random();

            for (int r = 0; r < 1000; r++)
            {
                var sd  = new SortedDeque <int>();
                var set = new HashSet <int>();
                for (int i = 0; i < 50; i++)
                {
                    for (var next = rng.Next(1000); !set.Contains(next);)
                    {
                        set.Add(next);
                        sd.TryAdd(next);
                    }
                }

                for (int i = 0; i < 1000; i++)
                {
                    for (var next = rng.Next(1000); !set.Contains(next);)
                    {
                        set.Add(next);
                        sd.TryAdd(next);
                    }

                    Assert.AreEqual(set.Count, sd.Count);
                    Assert.AreEqual(set.Sum(), sd.Sum());

                    var first = sd.RemoveFirst();
                    set.Remove(first);
                    Assert.AreEqual(set.Count, sd.Count);
                    Assert.AreEqual(set.Sum(), sd.Sum());
                    Assert.IsTrue(DequeIsSorted(sd));
                    var c    = 0;
                    var prev = 0;
                    foreach (var e in sd)
                    {
                        if (c == 0)
                        {
                            c++;
                            prev = e;
                        }
                        else
                        {
                            Assert.IsTrue(e > prev);
                            prev = e;
                        }
                    }
                }
            }
        }
示例#13
0
        void Main()
        {
            String digits = "123456789";
            permutation("", digits);
            HashSet<int> pandigitalNumbers = new HashSet<int>();

            foreach (string s in numbers)
            {
                int three = Convert.ToInt32(s.Substring(0, 3));
                int two = Convert.ToInt32(s.Substring(3, 2));

                int one = Convert.ToInt32(s.Substring(0, 1));
                int four = Convert.ToInt32(s.Substring(1, 4));

                int total = Convert.ToInt32(s.Substring(5, 4));

                if (three * two == total || one * four == total)
                {
                    Console.WriteLine("ADDING: " + s);
                    pandigitalNumbers.Add(total);
                }
            }

            Console.WriteLine(pandigitalNumbers.Sum());
        }
    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine());
        HashSet<House> Houses = new HashSet<House>();
        long amountOfCable = 0;
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            Houses.Add(new House { X = int.Parse(inputs[0]), Y = int.Parse(inputs[1]) });
        }

        //Core: Calculate Average House Y index
        double Avg = Houses.Sum(x => x.Y) / N;

        //Core:find the house closest to the Avg Y and use its Y coordinate
        int closest = Houses.OrderBy(x => Math.Abs(x.Y - Avg)).First().Y;

        //lay the mainline
        amountOfCable += (Houses.Max(x => x.X) - Houses.Min(x => x.X));

        //per other House calculate distance from location to mainline
        foreach (var i in Houses)
        {
            amountOfCable += i.Y > closest ? i.Y - closest : closest - i.Y;
        }

        // Write an action using Console.WriteLine()
        // To debug: Console.Error.WriteLine("Debug messages...");

        Console.WriteLine(amountOfCable);
    }
示例#15
0
        public static int Solve()
        {
            bool          shouldQuit = false;
            HashSet <int> products   = new HashSet <int>();

            for (int a = 2; shouldQuit == false; a++)
            {
                for (int b = a + 1; ; b++)
                {
                    tries++;

                    int n          = a * b;
                    int digitCount = DigitCount(a) + DigitCount(b) + DigitCount(n);

                    if (digitCount > 9)
                    {
                        if (b == a + 1)
                        {
                            shouldQuit = true;
                        }                                       // The smallest b is already too big; no point going higher
                        break;
                    }

                    if (digitCount == 9 && ArePandigital(a, b, n))
                    {
                        products.Add(n);
                        Debug.Print($"{a} x {b} = {n}");
                    }
                }
            }

            return(products.Sum());
        }
示例#16
0
        public void Solve()
        {
            List <int> multiplesOf3 = MultiplesBelow(3, 10);
            List <int> multiplesOf5 = MultiplesBelow(5, 10);

            var multiples = new HashSet <int>(multiplesOf3.Concat(multiplesOf5).ToList()).ToList();

            multiples.Sort();

            Console.WriteLine("Multiples of 3 or 5 under 10: ");

            Console.WriteLine(string.Join(",", multiples.ToArray()));

            Console.WriteLine("Sum: " + multiples.Sum());


            multiplesOf3 = MultiplesBelow(3, 1000);
            multiplesOf5 = MultiplesBelow(5, 1000);

            multiples = new HashSet <int>(multiplesOf3.Concat(multiplesOf5).ToList()).ToList();
            multiples.Sort();

            Console.WriteLine("Multiples of 3 or 5 under 1000: ");

            Console.WriteLine(string.Join(",", multiples.ToArray()));

            Console.WriteLine("Sum: " + multiples.Sum());
        }
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            HashSet <long> primeNumber = new HashSet <long>();

            for (int i = 1; i < 2000000; i++)
            //for (int i = 1; i < 1000; i++)
            {
                //if (isPrime(i))
                //if (isPrime2(i))
                if (isPrime3(i))
                {
                    //Console.WriteLine("{0}", i);
                    primeNumber.Add(i);
                }
            }

            Console.WriteLine("isPrime3 number sum {0}.", primeNumber.Sum());
            stopwatch.Stop();

            // Write result.
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
        }
示例#18
0
        static void Main()
        {
            var digits = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var matching = new HashSet<int>();

            var perms = digits.GetPermutations();
            Action<int[], int,int> a = (perm, i, j) =>
            {
                var multiplicand = DigitsToInt(perm, 0, i - 1);
                var multiplier = DigitsToInt(perm, i, i + j - 1);
                var product = DigitsToInt(perm, i + j, perm.Length - 1);

                if (multiplicand * multiplier == product)
                {
                    matching.Add(product);
                }
            };
            foreach (var perm in perms)
            {
                var permArray = perm.ToArray();
                a(permArray,1, 4);
                a(permArray,2, 3);
            }

            Console.WriteLine(matching.Sum());
            Console.ReadLine();
        }
示例#19
0
        public static int Solve(int n)
        {
            var options = new bool[n]; //options will be used to indicate available and used characters. n - 1 because we're starting from 1.

            Insert("", options);

            var products = new HashSet <int>();

            foreach (var option in _options)
            {
                for (var multiplyIndex = 1; multiplyIndex < option.Length - 2; multiplyIndex++)
                {
                    for (var equalityIndex = multiplyIndex + 2; equalityIndex < option.Length - 1; equalityIndex++)
                    {
                        var left  = int.Parse(option.Substring(0, multiplyIndex));
                        var right = int.Parse(option.Substring(multiplyIndex, equalityIndex - multiplyIndex));
                        var sum   = int.Parse(option.Substring(equalityIndex));

                        if (left * right == sum)
                        {
                            products.Add(sum);
                        }
                        else if (left * right > sum)
                        {
                            break;
                        }
                    }
                }
            }

            return(products.Sum());
        }
示例#20
0
        private (int, bool) Run(string input, int delay)
        {
            var lines = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(c => Regex.Match(c, @"(?<position>\d*):\s(?<size>\d*)"))
                        .Select(m => (int.Parse(m.Groups["position"].Value), int.Parse(m.Groups["size"].Value)))
                        .ToDictionary(c => c.Item1, c => c.Item2);

            int maxDepth = lines.Keys.Max() + 1;
            var firewall = new int[maxDepth];

            foreach (var item in lines)
            {
                firewall[item.Key] = item.Value;
            }

            var catched = new HashSet <int>();

            for (int i = 0; i < maxDepth; i++)
            {
                if (firewall[i] == 0)
                {
                    continue;
                }

                if ((i + delay) % ((firewall[i] - 1) * 2) == 0)
                {
                    catched.Add(i);
                }
            }

            return(catched.Sum(c => c * firewall[c]), catched.Any());
        }
示例#21
0
        public void Method()
        {
            Console.WriteLine("find the sum of all positive integers which cannot be written as the sum of two abundant numbers");
            // every number above 28123 can be written as the sum of two abundant numbers, so only iterate up to that point

            const int limit = 28124;

            // find all abundant numbers less than 28123
            for (int i = 1; i < limit; i++)
            {
                if (IsAbundant(i))
                {
                    abundantNumbers.Add(i);
                }
            }

            // find numbers that cannot be written as the sum of two abundant numbers
            HashSet <int> numbersNotSumOfTwoAbundants = new HashSet <int>();

            // iterate through each number up to limit
            for (int num = 1; num < limit; num++)
            {
                if (!IsAbundantSum(num))
                {
                    numbersNotSumOfTwoAbundants.Add(num);
                }
            }

            // sum all numbers that are not the sum of two abundant numbers
            int sum = numbersNotSumOfTwoAbundants.Sum();

            Console.WriteLine($"sum of all numbers less than {limit} that cannot be expressed as the sum of two abundant numbers: {sum}");
        }
示例#22
0
        public Board(int[] drawings, int[][] board)
        {
            WinningTurn    = drawings.Length;
            WinningSets[5] = new HashSet <int>();
            WinningSets[6] = new HashSet <int>();
            WinningSets[7] = new HashSet <int>();
            WinningSets[8] = new HashSet <int>();
            WinningSets[9] = new HashSet <int>();
            for (int i = 0; i < board.Length; i++)
            {
                WinningSets[i] = board[i].ToHashSet();
                for (int j = 0; j < board[i].Length; j++)
                {
                    availableValues.Add(board[i][j]);
                    WinningSets[5 + j].Add(board[i][j]);
                }
            }

            for (var turn = 0; turn < drawings.Length; turn++)
            {
                availableValues.Remove(drawings[turn]);
                foreach (var set in WinningSets)
                {
                    set.Remove(drawings[turn]);
                }
                if (WinningSets.Any(x => x.Count == 0))
                {
                    Score       = availableValues.Sum() * drawings[turn];
                    WinningTurn = turn;
                    break;
                }
            }
        }
示例#23
0
        /// <summary>
        /// Calculates the sum of the numbers n not exceeding 10^16 for which g(n) = n
        /// </summary>
        static void P548()
        {
            HashSet <long> ans = new HashSet <long>();

            for (int a = 1; a < 45; a++)
            {
                for (int b = 1; b < 5; b++)
                {
                    for (int c = 0; c < 2; c++)
                    {
                        for (int d = c; d < 2; d++)
                        {
                            for (int e = d; e < 2; e++)
                            {
                                for (int f = e; f < 2; f++)
                                {
                                    BigInteger n = getGozinta(new long[] { a, b, c, d, e, f });
                                    if (n < BigInteger.Pow(10, 16) && getGozinta(new long[] { (long)n }) == n)
                                    {
                                        ans.Add((long)n);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine(ans.Sum() + 1);
        }
示例#24
0
        void Main()
        {
            String digits = "123456789";

            permutation("", digits);
            HashSet <int> pandigitalNumbers = new HashSet <int>();

            foreach (string s in numbers)
            {
                int three = Convert.ToInt32(s.Substring(0, 3));
                int two   = Convert.ToInt32(s.Substring(3, 2));

                int one  = Convert.ToInt32(s.Substring(0, 1));
                int four = Convert.ToInt32(s.Substring(1, 4));

                int total = Convert.ToInt32(s.Substring(5, 4));

                if (three * two == total || one * four == total)
                {
                    Console.WriteLine("ADDING: " + s);
                    pandigitalNumbers.Add(total);
                }
            }

            Console.WriteLine(pandigitalNumbers.Sum());
        }
示例#25
0
        static void Main()
        {
            var buyers        = new HashSet <IBuyer>();
            int countOfPeople = int.Parse(Console.ReadLine());

            for (int i = 0; i < countOfPeople; i++)
            {
                var currentLine = Console.ReadLine().Split();

                if (currentLine.Length == 4)
                {
                    buyers.Add(new Citizen(currentLine[0], int.Parse(currentLine[1]), currentLine[2], currentLine[3]));
                }
                else if (currentLine.Length == 3)
                {
                    buyers.Add(new Rebel(currentLine[0], int.Parse(currentLine[1]), currentLine[2]));
                }
            }

            string command = null;

            while ((command = Console.ReadLine()) != "End")
            {
                var buyer = buyers.SingleOrDefault(x => x.Name == command);

                if (buyer != null)
                {
                    buyer.BuyFood();
                }
            }

            Console.WriteLine(buyers.Sum(x => x.Food));
        }
        public static IEnumerable <T2> ShuffleByHealth <T, T2>(this IEnumerable <T> items, Func <T, double> healthSelector, Func <T, T2> resultSelector)
        {
            var itemsWithHealth     = new HashSet <KeyValuePair <T, double> >(items.Select(x => new KeyValuePair <T, double>(x, healthSelector(x))));
            var totalItemListLength = itemsWithHealth.Count;

            for (var i = 0; i < totalItemListLength; i++)
            {
                var result    = default(T2);
                var healthSum = itemsWithHealth.Sum(h => h.Value);

                var valueFound  = false;
                var randomValue = ThreadLocalRandom.Instance.NextDouble();
                foreach (var itemWithHealth in itemsWithHealth)
                {
                    randomValue -= itemWithHealth.Value / healthSum;
                    if (randomValue < epsilon)
                    {
                        valueFound = true;
                        result     = resultSelector(itemWithHealth.Key);
                        itemsWithHealth.Remove(itemWithHealth);
                        break;
                    }
                }
                if (!valueFound)
                {
                    var last = itemsWithHealth.Last();
                    result = resultSelector(last.Key);
                    itemsWithHealth.Remove(last);
                }
                yield return(result);
            }
        }
示例#27
0
        public async Task <DividasFiltroModel> MontaRetornoDividas(DividasModel dividas)
        {
            var dividasRetorno = new DividasFiltroModel();

            await Task.Factory.StartNew(() => {
                var parcelas = new HashSet <ParcelasFiltroModel>();

                foreach (var item in dividas.parcelas.ToHashSet())
                {
                    parcelas.Add(new ParcelasFiltroModel()
                    {
                        num_parcela = item.num_parcela,
                        vencimento  = item.vencimento,
                        valor       = Math.Round(item.valor, 2),
                        valor_juros = Math.Round((dividas.perc_juros / 30) * (int)(DateTime.Today.Subtract(item.vencimento).TotalDays) * item.valor, 2)
                    });
                }

                dividasRetorno.numero_titulo    = dividas.numero_titulo;
                dividasRetorno.nome             = dividas.nome;
                dividasRetorno.qtd_parcelas     = dividas.parcelas.Count();
                dividasRetorno.valor_original   = Math.Round(dividas.parcelas.Sum(p => p.valor), 2);
                dividasRetorno.dias_atraso      = (int)(DateTime.Today.Subtract(dividas.parcelas.Min(p => p.vencimento)).TotalDays);
                dividasRetorno.valor_atualizado = Math.Round((parcelas.Sum(p => p.valor_juros) + dividasRetorno.valor_original) + (dividasRetorno.valor_original *dividas.perc_multa), 2);
                dividasRetorno.parcelas         = parcelas;
            });

            return(dividasRetorno);
        }
示例#28
0
        static int A(string intialState, Dictionary <string, string> transformations)
        {
            HashSet <int> currentState = new HashSet <int>();
            int           minIndex     = 0;
            int           maxIndex     = initial_state.Length - 1;

            for (int i = 0; i < initial_state.Length; i++)
            {
                if (initial_state[i] == '#')
                {
                    currentState.Add(i);
                }
            }
            foreach (var generation in Enumerable.Range(1, 20))
            {
                minIndex--; maxIndex++;
                var nextState = new HashSet <int>();
                for (int i = minIndex; i <= maxIndex; i++)
                {
                    string surrounding = (currentState.Contains(i - 2) ? "#" : ".")
                                         + (currentState.Contains(i - 1) ? "#" : ".")
                                         + (currentState.Contains(i - 0) ? "#" : ".")
                                         + (currentState.Contains(i + 1) ? "#" : ".")
                                         + (currentState.Contains(i + 2) ? "#" : ".");
                    if (transformations[surrounding] == "#")
                    {
                        nextState.Add(i);
                    }
                }
                currentState = nextState;
            }
            return(currentState.Sum());
        }
        public double Evaluate(IEnumerable <PieceData> pieces)
        {
            HashSet <PieceData> hasChecked = new HashSet <PieceData>();

            List <int> counts = new List <int>();

            foreach (var piece in pieces)
            {
                if (piece == null)
                {
                    continue;
                }
                if (piece.m_shape != m_shape)
                {
                    continue;
                }
                if (hasChecked.Contains(piece))
                {
                    continue;
                }

                HashSet <PieceData> group = CombinationUtility.GetGroup(piece, x => x.m_shape == m_shape);
                counts.Add(group.Sum(x => x.m_positions.Length));
                hasChecked.UnionWith(group);
            }

            OnGroupChecked?.Invoke(this, counts);
            var value = (counts.Count == 0) ? 0 : counts.Average();

            OnEvaluated?.Invoke(this, value);
            return(value);
        }
示例#30
0
        public static void PrepareRequestWithMultipleIds(StringBuilder pathBuilder, HttpRequestMessage request, string[] ids, JsonOperationContext context)
        {
            var uniqueIds = new HashSet <string>(ids);
            // if it is too big, we drop to POST (note that means that we can't use the HTTP cache any longer)
            // we are fine with that, requests to load > 1024 items are going to be rare
            var isGet = uniqueIds.Sum(x => x.Length) < 1024;

            if (isGet)
            {
                uniqueIds.ApplyIfNotNull(id => pathBuilder.Append($"&id={Uri.EscapeDataString(id)}"));
            }
            else
            {
                request.Method = HttpMethod.Post;

                request.Content = new BlittableJsonContent(stream =>
                {
                    using (var writer = new BlittableJsonTextWriter(context, stream))
                    {
                        writer.WriteStartObject();
                        writer.WriteArray("Ids", uniqueIds);
                        writer.WriteEndObject();
                    }
                });
            }
        }
示例#31
0
        public void CompletePostSerialization(TessellatedSolid ts)
        {
            Faces = new HashSet <PolygonalFace>();
            foreach (var i in _faceIndices)
            {
                var face = ts.Faces[i];
                Faces.Add(face);
                face.BelongsToPrimitive = this;
            }
            Vertices = new List <Vertex>();
            foreach (var i in _vertexIndices)
            {
                Vertices.Add(ts.Vertices[i]);
            }

            _innerEdges = new List <Edge>();
            foreach (var i in _innerEdgeIndices)
            {
                _innerEdges.Add(ts.Edges[i]);
            }

            _outerEdges = new List <Edge>();
            foreach (var i in _outerEdgeIndices)
            {
                _outerEdges.Add(ts.Edges[i]);
            }
            Area = Faces.Sum(f => f.Area);
        }
示例#32
0
    public override void PartOne(IInput input, IOutput output)
    {
        var map = input.As2DPoints()
                  .ToImmutableDictionary(k => k.Point, v => v.Character - '0');

        var lowPoints = new HashSet <Point2d>();

        foreach (var(point, height) in map)
        {
            var neighbours = PointHelpers
                             .GetDirectNeighbours(point);

            var lowest = neighbours                                                                               // Go through all possible neighbours
                         .Select(n => map.TryGetValue(n, out var neighbourHeight) ? neighbourHeight : (int?)null) // Get their height or null for missing.
                         .Where(n => n is not null)
                         .All(neighbourHeight => height < neighbourHeight);

            if (lowest)
            {
                lowPoints.Add(point);
            }
        }

        var score = lowPoints
                    .Sum(point => 1 + map[point]);

        output.WriteProperty("Risk Level", score);
    }
示例#33
0
        static void Main(string[] args)
        {
            Dictionary<int, int> sums = new Dictionary<int, int>();

            sums.Add(0, 0);

            foreach (int n in Enumerable.Range(1, 10000))
            {
                if(sums.ContainsKey(n)== false)
                {
                    sums.Add(n, GetSumOfDivisors(n));
                }

                if(sums.ContainsKey(sums[n]) == false)
                {
                    sums.Add(sums[n], GetSumOfDivisors(sums[n]));
                }
            }

            HashSet<int> amicables = new HashSet<int>();
            foreach (var item in sums)
            {
                if (item.Key > 10000)
                    continue;

                if(item.Key == sums[item.Value] && item.Key != item.Value)
                {
                    amicables.Add(item.Key);
                    amicables.Add(item.Value);
                }
            }
            Console.WriteLine(amicables.Sum());
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ').ToArray();
            Dictionary <string, HashSet <int> > data = new Dictionary <string, HashSet <int> >();

            while (input[0] != "Aggregate")
            {
                string place = input[0];
                int    space = int.Parse(input[1]);

                if (!data.ContainsKey(place))
                {
                    data.Add(place, new HashSet <int>());
                }
                data[place].Add(space);
                input = Console.ReadLine().Split(' ').ToArray();
            }
            foreach (KeyValuePair <string, HashSet <int> > shellPlace in data)
            {
                string        plac         = shellPlace.Key;
                HashSet <int> spac         = shellPlace.Value;
                double        subtractAver = spac.Sum() - Math.Truncate(spac.Average());

                ; Console.WriteLine($"{plac} -> {string.Join(", ", spac)} ({subtractAver})");
            }
        }
        static void Main()
        {
            var collection = new HashSet<double> { 5.2, 8, -3.14, 0, 55 };

            Console.WriteLine(collection.Sum());
            Console.WriteLine(collection.Product());
            Console.WriteLine(collection.Min());
            Console.WriteLine(collection.Max());
            Console.WriteLine(collection.Average());
        }
示例#36
0
 private string Main()
 {
     permutation("", "123456789");
     HashSet<int> pandigitalNumbers = new HashSet<int>();
     foreach (string s in numbers.AsParallel().Where(
                                x => Convert.ToInt32(x.Substring(0, 3)) * Convert.ToInt32(x.Substring(3, 2)) == Convert.ToInt32(x.Substring(5, 4))
                                  || Convert.ToInt32(x.Substring(0, 1)) * Convert.ToInt32(x.Substring(1, 4)) == Convert.ToInt32(x.Substring(5, 4))))
         pandigitalNumbers.Add(Convert.ToInt32(s.Substring(5, 4)));
     return pandigitalNumbers.Sum().ToString();
 }
示例#37
0
        public int S(int n)
        {
            var set = new HashSet<int>();
            for(int k=2;k<=n;k++)
            {
                set.Add(mps(k));
            }

            return set.Sum();
        }
示例#38
0
        public long Solve()
        {
            var primes = new Utils.Prime(51L);
            var squereFree = new HashSet<long>();
            for (var row = 1; row <= 50; row++)
            {
                for (var number = 1; number <= row; number++)
                {
                    squereFree.Add(this.GetSquereFreeBinomilaNumber(number, row, primes));
                }
            }

            return squereFree.Sum();
        }
        public int CalculateSum(int upperLimit)
        {
            var uniqueMultiples = new HashSet<int>();

            for (int i = 0; i < upperLimit; i++)
            {
                if (i%3 == 0 || i%5 == 0)
                {
                    uniqueMultiples.Add(i);
                }
            }

            var sum = uniqueMultiples.Sum();
            return sum;
        }
示例#40
0
 private static int GetSumOfDivisors(int n)
 {
     int sq = (int) Math.Sqrt(n);
     HashSet<int> divisors = new HashSet<int>();
     for(int i = 1; i <= sq; i++)
     {
         if(n % i == 0)
         {
             divisors.Add(i);
             divisors.Add(n / i);
         }
     }
     divisors.Remove(n);
     return divisors.Sum();
 }
示例#41
0
		public P032 ()
		{
			ulong max = 987654321 / 2;
			var all = new HashSet<ulong> ();

			for (ulong a = max; a > 0; a--) {
				if (false
					|| (a % 10000000 == 0)
					|| (a < 10000000 && a % 100000 == 0)
					|| (a < 1000000 && a % 10000 == 0)
					|| (a < 100000 && a % 1000 == 0)
					|| (a < 10000 && a % 100 == 0)
					|| (a < 1000 && a % 10 == 0)
					|| (a < 100 && a % 1 == 0)
					) {
					Console.WriteLine ("a = " + a);
				}

				if (0 == Pandigital.Is1to9Pandigital (a)) {
					continue;
				}
				if (a % 10 == 1) {
					// x1 * yz = ??z
					continue;
				}

				for (ulong b = a; b <= max / a; b++) {
					if (b % 10 == 1) {
						// x1 * yz = ??z, thus can never be pandigital
						continue;
					}

					ulong c = a * b;
					var pan = Pandigital.Is1to9Pandigital (a, b, c);
					if (9 != pan) {
						continue;
					}
					all.Add (c);
					Console.WriteLine (a + " x " + b + " = " + c + "\t\ttotal: " + all.Count + ", sum " + all.Sum (x => (long) x));
				}
			}
		}
示例#42
0
        public static int Answer()
        {
            var d = Util.Memoize<int, int>(n => MathEx.Divisors(n).Where(i => i != n).Sum());
            var amicableNumbers = new HashSet<int>();
            int max = 9999;

            for (int a = 1; a <= max; a++)
            {
                for (int b = a; b <= max; b++)
                {
                    if (a != b && d(a) == b && d(b) == a)
                    {
                        amicableNumbers.Add(a);
                        amicableNumbers.Add(b);
                    }
                }
            }

            return amicableNumbers.Sum();
        }
示例#43
0
        public void Solve() {
            HashSet<int> p = new HashSet<int>();  //guarantees uniqueness of items

            foreach (var i in 2.To(100)) {
                int start = 1234;

                if (i > 9)
                    start = 123;

                foreach (var j in start.To(10000 / i + 1)) {
                    string s = (i.ToString() + j.ToString() + (i * j).ToString());
                    if (s.ToLong().IsPanDigital()) {
                        p.Add(i * j);
                    }
                }
            }

            Util.WL("The sum of all products whose multiplicand/multiplier/product\nidentity can be written as a 1 through 9 pandigital is {0}"
                .FormatWith(p.Sum()));
        }
示例#44
0
        public long Solve()
        {
            var values = new HashSet<long> { 1 };

            for (var number = 2L; number <= Math.Sqrt(Limit); number++)
            {
                var powerSpecial = number * number;
                var sumSpecial = number + powerSpecial;

                while ((sumSpecial + 1) <= Limit)
                {
                    values.Add(sumSpecial + 1);

                    powerSpecial = powerSpecial * number;
                    sumSpecial = sumSpecial + powerSpecial;
                }
            }

            return values.Sum();
        }
示例#45
0
 static void Main(string[] args)
 {
     HashSet<int> results = new HashSet<int>();
     for(int n = 2; n < 50000; n++)
     {
         for(int m = 2; m <= Math.Sqrt(n); m++)
         {
             if(n % m == 0)
             {
                 int p = n / m;
                 if(is9PalindromicTriplet(n, m, p))
                 {
                     results.Add(n);
                     Console.WriteLine(n + " = " + m + " * " + p);
                 }
             }
         }
     }
     Console.WriteLine(results.Sum());
     Console.ReadLine();
 }
示例#46
0
文件: Program.cs 项目: jamiees2/Euler
        static void Main(string[] args)
        {
            HashSet<int> amicableNumbers = new HashSet<int>();

            for (int i = 220; i < 10000; i++)
            {
                if (amicableNumbers.Contains(i)) continue;
                int sum = Factorize(i).Sum();
                int sumCheck = Factorize(sum).Sum();
                if (sumCheck == i && sum != i)
                {
                    Console.WriteLine(i + " " + sum);
                    amicableNumbers.Add(i);
                    amicableNumbers.Add(sum);
                }

            }
            Console.WriteLine();
            Console.WriteLine(amicableNumbers.Sum());
            Console.ReadKey();
        }
示例#47
0
		public P125 ()
		{
			ulong max = 100000000;
			var set = new HashSet<ulong> ();

			for (ulong start = 1; start < max; start++) {
				ulong sum = start * start;

				for (ulong cur = start + 1; ; cur++) {
					sum += cur * cur;
					if (sum >= max) {
						break;
					}
					if (Palindrome.IsPalindrome (sum)) {
						Console.WriteLine (sum + "\t" + start + "\t" + cur);
						set.Add (sum);
					}
				}
			}

			Console.WriteLine (set.Sum (x => (long) x));
		}
示例#48
0
        static void Main(string[] args)
        {
            var all = CombinatoricsUtilities.Permutations(Enumerable.Range(1, 9));

            var magicProducts = new HashSet<int>();

            foreach (var permutation in all.Select(p => string.Join("", p)))
            {
                // X1 X2 X3 ... X9
                // can multiply and equality signs be placed to form valid equation?
                // X1 x X2 X3 X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 x X3 X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 X3 x X3 X4 = X5 X6 X7 X8 X9
                // X1 X2 X3 X3 x X4 = X5 X6 X7 X8 X9

                for (int multLoc = 1; multLoc < 9 - 2; multLoc++)
                {
                    for (int equalsLoc = multLoc + 1; equalsLoc < 9; equalsLoc++)
                    {
                        // check that it forms correct equation
                        // a x b = c

                        int a = int.Parse(permutation.Substring(0, multLoc));
                        int b = int.Parse(permutation.Substring(multLoc, equalsLoc - multLoc));
                        int c = int.Parse(permutation.Substring(equalsLoc));

                        if (a * b == c)
                        {
                            string.Format("{0} x {1} = {2}", a, b, c).Dump();

                            magicProducts.Add(c);
                        }
                    }
                }
            }

            magicProducts.Sum().Dump("Answer");
        }
示例#49
0
        public long Solve()
        {
            var allSums = new HashSet<long>();

            for (var start = 1L; start <= 10000L; start++)
            {
                var sum = start * start;
                for (var next = start + 1; next <= 10000L; next++)
                {
                    sum += next * next;

                    if (sum > Max)
                        break;

                    if (this.IsPalindrom(sum))
                    {
                        Console.WriteLine("{0} - {1} {2}", start, next, sum);
                        allSums.Add(sum);
                    }
                }
            }

            return allSums.Sum();
        }
示例#50
0
        public override string GetAnswer()
        {
            HashSet<int> datas = new HashSet<int>();

            StringBuilder str = new StringBuilder();

            for (int i = 2; i <= 10000; i++) {
                int d1 = functionD(i);
                if (i == functionD(d1) && i != d1) {
                    datas.Add(i);
                    str.AppendFormat("친화수 쌍 : {0}, {1}", i, d1);
                    str.AppendLine();
                }
            }

            str.AppendFormat("친화수 ({0}개) : ", datas.Count);
            foreach(int data in datas) {
                str.AppendFormat("{0}, ", data);
            }
            str.AppendLine();
            str.AppendFormat("총합 : {0}", datas.Sum());

            return str.ToString();
        }
示例#51
0
文件: Program.cs 项目: jamiees2/Euler
        static void Main(string[] args)
        {
            HashSet<int> numbers = new HashSet<int>();
            for (int k = 2; k <= 12; k++)
            {
                for (int i = k; i <= k * k; i++)
                {
                    List<int> factors = i.PrimeFactors().ToList();
                    while(factors.Count < k)
                    {
                        factors.Add(1);
                    }
                    factors.Sort();
                    int j = factors.Count - 1;
                    while (factors[j] != 1 && factors.Sum() != factors.Product())
                    {
                        factors[j - 1] = factors[j] * factors[j - 1];
                        factors.Remove(factors[j]);
                        factors.Insert(0, 1);
                        j--;
                    }

                    if (factors.Sum() == factors.Product())
                    {
                        Console.WriteLine(k + " " + i + "    " + factors.ToStringPretty());
                        if (! numbers.Contains(i))
                        {
                            numbers.Add(i);
                        }
                        break;
                    }
                }
            }
            Console.WriteLine(numbers.Sum());
            Console.ReadKey();
        }
示例#52
0
        void Main()
        {
            // Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

            HashSet<int> pandigital = new HashSet<int>();

            for (int i = 1000; i < 10000; i++)
            {
                String s = Convert.ToString(i);
                if (!s.Contains("0") && (s.ToCharArray().Count() == s.ToCharArray().Distinct().Count()))
                {
                    if (IsPandigital(i))
                    {
                        Console.WriteLine("Adding: " + i);
                        pandigital.Add(i);
                    }
                }
            }

            Console.WriteLine("Sum: " + pandigital.Sum());
        }
示例#53
0
		private static string ResponseStatusAll(ulong steamID) {
			if (steamID == 0) {
				Logging.LogNullError(nameof(steamID));
				return null;
			}

			if (!IsOwner(steamID)) {
				return null;
			}

			HashSet<Bot> botsRunning = new HashSet<Bot>(Bots.Where(bot => bot.Value.KeepRunning).OrderBy(bot => bot.Key).Select(bot => bot.Value));
			IEnumerable<string> statuses = botsRunning.Select(bot => bot.ResponseStatus(steamID));

			return Environment.NewLine +
				string.Join(Environment.NewLine, statuses) + Environment.NewLine +
				"There are " + botsRunning.Count + "/" + Bots.Count + " bots running, with total of " + botsRunning.Sum(bot => bot.CardsFarmer.GamesToFarm.Count) + " games (" + botsRunning.Sum(bot => bot.CardsFarmer.GamesToFarm.Sum(game => game.CardsRemaining)) + " cards) left to farm.";
		}
示例#54
0
        protected override long GetCalculationResult()
        {
            const int max = 100000;
            const int halfmax = max / 2;

            var squares = new List<long>(halfmax) { 0 };

            for (int i = 1; i < halfmax; i++)
            {
                squares.Add(i * i);
            }

            var result = new HashSet<long>();

            for (int i = 1; i < squares.Count; i++)
            {
                for (int j = 1; j < squares.Count; j++)
                {
                    long res = squares[i] + squares[j];
                    if (squares.Contains(res))
                    {
                        long l = i + j + (int)Math.Sqrt(res);
                        if (!result.Contains(l))
                        {
                            //Print(
                            //    "{6} - {0}^2 + {1}^2 == {2} ({3} + {4} == {5})",
                            //    i,
                            //    j,
                            //    Math.Sqrt(res),
                            //    squares[i],
                            //    squares[j],
                            //    res,
                            //    l);
                            result.Add(l);
                        }
                    }
                    if (res > halfmax)
                    {
                        break;
                        Print("{0}", i);
                    }
                }
            }

            return result.Sum();
        }
        private static Dictionary<int, double> CalculateComponentFunctionValues(Graph graph,
            Dictionary<Vertex, int> components)
        {
            Dictionary<int, double> fValues = new Dictionary<int, double>();
            foreach (var componentNumber in components.Values.Distinct())
            {
                //Get all edges in this component
                HashSet<Edge> edgesInComponent = new HashSet<Edge>();
                var verticesInComponent = components.Where(x => x.Value == componentNumber).Select(x => x.Key);
                var nrOfTerminals = verticesInComponent.Count(x => graph.Terminals.Contains(x));
                foreach (var v in verticesInComponent)
                {
                    foreach (var e in graph.GetEdgesForVertex(v))
                        edgesInComponent.Add(e);
                }

                if (edgesInComponent.Count > 0)
                {
                    double fVal = edgesInComponent.Sum(x => x.Cost)/Math.Pow(nrOfTerminals, 2);
                    fValues.Add(componentNumber, fVal);
                }
                else
                    fValues.Add(componentNumber, double.MaxValue);
            }
            return fValues;
        }
示例#56
0
 private double JL(HashSet<int> labelled)
 {
     return labelled.Sum(index => JL_ii(index));
 }
示例#57
0
 private double JU(HashSet<int> unlabelled)
 {
     return unlabelled.Sum(index => JU_ii(index));
 }
        public string Solve()
        {
            Func<string, int> getFitness = child =>
            {
                var queenLocations = new HashSet<Point>(child.Select(x => x.ToPoint(GeneSet, BoardWidth)));
                int fitness = queenLocations.Sum(x => CountQueensAttacked(GetAttackablePoints(x), queenLocations));
                fitness += 10000 * (GeneCount - queenLocations.Count);
                return fitness;
            };

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            Action<int, int, string, string> displayCurrentBest =
                (generation, fitness, genes, strategy) =>
                {
                    var board = new char?[BoardHeight, BoardWidth];

                    foreach (var queenLocation in genes.Select(x => x.ToPoint(GeneSet, BoardWidth)))
                    {
                        board[queenLocation.X, queenLocation.Y] = 'Q';
                    }

                    for (int i = 0; i < BoardHeight; i++)
                    {
                        for (int j = 0; j < BoardWidth; j++)
                        {
                            Console.Write(board[i, j] ?? '.');
                            Console.Write(' ');
                        }
                        Console.WriteLine();
                    }
                    Console.WriteLine("generation\t{0} fitness\t{1} elapsed: {2}",
                                      generation.ToString().PadLeft(5, ' '),
                                      fitness.ToString().PadLeft(2, ' '),
                                      stopwatch.Elapsed);
                };
            var geneticSolver = new GeneticSolver
            {
                GetCanonicalGenes = GetCanonicalGenes,
                MaxSecondsWithoutImprovement = 5
            };
            string result = geneticSolver.GetBest(GeneCount,
                                                  GeneSet,
                                                  getFitness,
                                                  displayCurrentBest);
            Console.WriteLine(result);
            return getFitness(result) == 0
                       ? GetCanonicalGenes(result)
                       : null;
        }
示例#59
0
        public PoiType TakePoiByDistribution(HashSet<PoiType> poiSet)
        {
            if (_poiTypesDistributionDict == null)
            {
                _poiTypesDistributionDict = new Dictionary<PoiType, double>();

                var totalFrequency = poiSet.Sum(poiType => poiType.Frequency);
                var orderedPois = poiSet.OrderBy(p => p.Frequency);

                double currentFreq = 0;

                foreach (var poiType in orderedPois)
                {
                    currentFreq += poiType.Frequency/totalFrequency;
                    _poiTypesDistributionDict.Add(poiType, currentFreq);
                }
            }

            var d = _random.NextDouble();

            return (from dictEntry in _poiTypesDistributionDict where d <= dictEntry.Value select dictEntry.Key).FirstOrDefault();
        }
示例#60
0
        public static int spiralSum(int size)
        {
            List<List<int>> grid = new List<List<int>>(size);
            for (int i = 0; i < size; i++) {
                grid.Add(new List<int>(size));
                for (int j = 0; j < size; j++) {
                    grid[i].Add(0);
                }
            }
            Direction dir = Direction.Left;
            bool filled = false;
            int currentNumber = size * size;
            int currentSize = size;
            int numMade = 0;
            int x = size - 1;
            int y = 0;

            while (filled == false) {
                grid[y][x] = currentNumber;
                currentNumber--;
                numMade++;
                if (currentNumber == 0) {
                    filled = true;
                }
                if (numMade == currentSize) {
                    numMade = 0;
                    switch (dir) {
                        case Direction.Left:
                            dir = Direction.Down;
                            currentSize--;
                            break;
                        case Direction.Down:
                            dir = Direction.Right;
                            break;
                        case Direction.Right:
                            dir = Direction.Up;
                            currentSize--;
                            break;
                        case Direction.Up:
                            dir = Direction.Left;
                            break;
                    }
                }
                switch (dir) {
                    case Direction.Left:
                        x--;
                        break;
                    case Direction.Down:
                        y++;
                        break;
                    case Direction.Right:
                        x++;
                        break;
                    case Direction.Up:
                        y--;
                        break;
                }
            }
            int sum = 0;
            x = 0;
            y = 0;
            HashSet<int> nums = new HashSet<int>();
            while (y < size && x < size) {
                /*Console.Write(grid[y][x]);
                Console.Write(", ");*/
                nums.Add(grid[y][x]);
                x++;
                y++;
            }
            //Console.WriteLine();
            x = size - 1;
            y = 0;
            while (y < size && x >= 0) {
                //Console.Write("{0}, ", grid[y][x]);
                nums.Add(grid[y][x]);
                y++;
                x--;
            }
            sum = nums.Sum();
               // Console.WriteLine();

            return sum;
        }