Ejemplo n.º 1
0
        private IllustrationPointTreeNode BuildFaultTree(
            Tuple <int, WindDirection, int, string> windDirectionClosingSituation,
            int faultTreeId,
            CombinationType combinationType,
            IEnumerable <Tuple <int?, int, Type, CombinationType> > results)
        {
            var dataKey = new ThreeKeyIndex(windDirectionClosingSituation.Item1, windDirectionClosingSituation.Item3, faultTreeId);
            var faultTreeIllustrationPointStochasts = new List <Stochast>();

            if (!faultTreeBetaValues.ContainsKey(dataKey))
            {
                return(null);
            }

            if (faultTreeStochasts.ContainsKey(dataKey))
            {
                AddRange(faultTreeIllustrationPointStochasts, faultTreeStochasts[dataKey]);
            }

            var illustrationPoint = new FaultTreeIllustrationPoint(faultTrees[faultTreeId],
                                                                   faultTreeBetaValues[dataKey],
                                                                   faultTreeIllustrationPointStochasts,
                                                                   combinationType);

            var node = new IllustrationPointTreeNode(illustrationPoint);

            node.SetChildren(results.Where(r => r.Item1 == faultTreeId)
                             .Select(child => child.Item3 == typeof(FaultTreeIllustrationPoint)
                                                         ? BuildFaultTree(windDirectionClosingSituation, child.Item2, child.Item4, results)
                                                         : BuildSubMechanism(windDirectionClosingSituation, child.Item2)).ToArray());
            return(node);
        }
        /// <summary>
        /// Creates a new instance of <see cref="FaultTreeIllustrationPoint"/> based on the
        /// information of <paramref name="hydraRingFaultTreeIllustrationPoint"/>.
        /// </summary>
        /// <param name="hydraRingFaultTreeIllustrationPoint">The <see cref="HydraRingFaultTreeIllustrationPoint"/>
        /// to base the <see cref="FaultTreeIllustrationPoint"/> to create on.</param>
        /// <returns>The newly created <see cref="FaultTreeIllustrationPoint"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="hydraRingFaultTreeIllustrationPoint"/>
        /// is <c>null</c>.</exception>
        /// <exception cref="IllustrationPointConversionException">Thrown when the <paramref name="hydraRingFaultTreeIllustrationPoint"/>
        /// cannot be converted to a <see cref="FaultTreeIllustrationPoint"/>.</exception>
        public static FaultTreeIllustrationPoint Convert(HydraRingFaultTreeIllustrationPoint hydraRingFaultTreeIllustrationPoint)
        {
            if (hydraRingFaultTreeIllustrationPoint == null)
            {
                throw new ArgumentNullException(nameof(hydraRingFaultTreeIllustrationPoint));
            }

            try
            {
                CombinationType        combinationType = CombinationTypeConverter.Convert(hydraRingFaultTreeIllustrationPoint.CombinationType);
                IEnumerable <Stochast> stochasts       = hydraRingFaultTreeIllustrationPoint.Stochasts
                                                         .Select(StochastConverter.Convert)
                                                         .ToArray();

                return(new FaultTreeIllustrationPoint(hydraRingFaultTreeIllustrationPoint.Name,
                                                      hydraRingFaultTreeIllustrationPoint.Beta,
                                                      stochasts,
                                                      combinationType));
            }
            catch (Exception e) when(e is NotSupportedException || e is InvalidEnumArgumentException)
            {
                string errorMessage = $"Could not convert the {typeof(HydraRingCombinationType)} into a {typeof(CombinationType)}.";

                throw new IllustrationPointConversionException(errorMessage, e);
            }
        }
Ejemplo n.º 3
0
 public Combination(CombinationType combinationType, int[] dice)
 {
     CombinationType = combinationType;
     Dice            = dice;
     Score           = dice.Sum();
     Completed       = false;
 }
Ejemplo n.º 4
0
        public CardSet(Card[] cards, bool canBeFlush)
        {
            if (cards.Length != CARDS_COUNT || cards[0].Number > cards[1].Number)
            {
                throw new Exception();
            }

            _cards = cards;

            _index = Powers13[0] * (int)_cards[0].Number * (25 - (int)_cards[0].Number) / 2;
            for (int i = 1; i < CARDS_COUNT; i++)
            {
                _index += (int)_cards[i].Number * Powers13[i - 1];
            }

            Type    = (CombinationType)(FromTable[_index] >> 12);
            _kicker = new[] { (NumberType)((FromTable[_index] >> 8) & 15), (NumberType)((FromTable[_index] >> 4) & 15), (NumberType)(FromTable[_index] & 15) };

            if (canBeFlush)
            {
                var flushes = _cards.GroupBy(c => c.Flush);
                if (flushes.Any(g => g.Count() >= 5))
                {
                    IsFlush(flushes.First(g => g.Count() >= 5).Select(c => c.Number).OrderByDescending(n => n).ToArray());
                }
            }
        }
Ejemplo n.º 5
0
        private static string CreateExpectedGraphConnectingNodeContent(CombinationType combinationType)
        {
            string name = combinationType == CombinationType.And
                              ? "En"
                              : "Of";

            return($"<text>{name}</text>");
        }
Ejemplo n.º 6
0
 internal Combination(
     CombinationType _Type,
     IEnumerable <Cell> _Cells
     )
 {
     Type  = _Type;
     Cells = _Cells;
 }
Ejemplo n.º 7
0
 public Combination(double power, CombinationType type, double behaviourPower, IList<ICard> combinationCardsCollection, IList<ICard> kickersCollection)
 {
     this.Power = power;
     this.Type = type;
     this.BehaviourPower = behaviourPower;
     this.CombinationCardsCollection = combinationCardsCollection;
     this.KickersCollection = kickersCollection;
 }
Ejemplo n.º 8
0
        public void Convert_HydraRingCombinationType_ReturnCombinationType(HydraRingCombinationType hydraRingCombinationType,
                                                                           CombinationType expectedCombinationType)
        {
            // Call
            CombinationType combinationType = CombinationTypeConverter.Convert(hydraRingCombinationType);

            // Assert
            Assert.AreEqual(expectedCombinationType, combinationType);
        }
Ejemplo n.º 9
0
 public Combination(double power, CombinationType type, double behaviourPower,
                    IList <ICard> combinationCardsCollection, IList <ICard> kickersCollection)
 {
     this.Power                      = power;
     this.Type                       = type;
     this.BehaviourPower             = behaviourPower;
     this.CombinationCardsCollection = combinationCardsCollection;
     this.KickersCollection          = kickersCollection;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Spawns a new SoX process using the specified options in this instance and plays the specified files.
        /// </summary>
        /// <param name="inputFiles">Audio files to be played.</param>
        /// <param name="combination">How to combine the input files.</param>
        public void Play(string[] inputFiles, CombinationType combination)
        {
            var inputs = new List <InputFile>(inputFiles.Length);

            foreach (var inputFile in inputFiles)
            {
                inputs.Add(new InputFile(inputFile));
            }

            Process(inputs.ToArray(), "--default-device", combination);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Spawns a new SoX process using the specified options in this instance.
        /// </summary>
        /// <param name="inputFiles">Audio files to be processed.</param>
        /// <param name="outputFile">Output file.</param>
        /// <param name="combination">How to combine the input files.</param>
        public void Process(string[] inputFiles, string outputFile, CombinationType combination)
        {
            var inputs = new List <InputFile>(inputFiles.Length);

            foreach (var inputFile in inputFiles)
            {
                inputs.Add(new InputFile(inputFile));
            }

            Process(inputs.ToArray(), outputFile, combination);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a new instance of <see cref="FaultTreeIllustrationPoint"/>.
        /// </summary>
        /// <param name="name">The name of the illustration point node.</param>
        /// <param name="beta">The beta value of this illustration point.</param>
        /// <param name="stochasts">A collection of <see cref="Stochasts"/>
        /// that are associated with this illustration point node.</param>
        /// <param name="combinationType">The way to combine two nodes into a single
        /// tree node element in the fault tree.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="name"/> or
        /// <paramref name="stochasts"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown when the <see cref="stochasts"/> aren't unique.</exception>
        public FaultTreeIllustrationPoint(string name,
                                          double beta,
                                          IEnumerable <Stochast> stochasts,
                                          CombinationType combinationType)
            : base(name, beta)
        {
            if (stochasts == null)
            {
                throw new ArgumentNullException(nameof(stochasts));
            }

            StochastValidator.ValidateStochasts(stochasts);

            CombinationType = combinationType;
            Stochasts       = stochasts;
        }
Ejemplo n.º 13
0
        public static IEnumerable <ITuple> ComputeTupleProducts(
            IList <IDomain> domains,
            CombinationType combinationType)
        {
            switch (combinationType)
            {
            case CombinationType.PairWize:
                return(Products.PairWize(domains));

            case CombinationType.Cartesian:
                return(Products.Cartesian(domains));

            default:
                throw new NotSupportedException(combinationType.ToString());
            }
        }
Ejemplo n.º 14
0
        private void IsFlush(NumberType[] kickers)
        {
            var newKickers = kickers;

            Array.Sort(newKickers);
            Array.Reverse(newKickers);

            if (Type != CombinationType.STRAIGHT)
            {
                _kicker = newKickers.Take(5).ToArray();
                Type    = CombinationType.FLUSH;
            }
            else
            {
                bool isStraight = false;
                for (int i = 0; i <= newKickers.Length - COMMON_CARDS_COUNT; i++)
                {
                    if (isStraight |= ((int)newKickers[i] == (int)newKickers[i + 4] + 4))
                    {
                        if (newKickers[i] == NumberType.A)
                        {
                            Type = CombinationType.ROYAL_FLUSH;
                        }
                        else
                        {
                            Type = CombinationType.STRAIGHT_FLUSH;
                        }
                        _kicker = new[] { newKickers[i] };
                        break;
                    }
                }

                if (!isStraight)
                {
                    if (newKickers[0] == NumberType.A && newKickers[newKickers.Length - 4] == NumberType._5 && newKickers[newKickers.Length - 1] == NumberType._2)
                    {
                        Type    = CombinationType.STRAIGHT_FLUSH;
                        _kicker = new[] { NumberType._5 };
                    }
                    else
                    {
                        _kicker = newKickers.Take(5).ToArray();
                        Type    = CombinationType.FLUSH;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a new instance of <see cref="FaultTreeIllustrationPoint"/>.
        /// </summary>
        /// <param name="name">The name of the fault tree illustration point</param>
        /// <param name="beta">The combined beta values of its children.</param>
        /// <param name="stochasts">The combined stochasts of its children.</param>
        /// <param name="combinationType">The way in which the sub illustration points are combined.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="name"/> is <c>null</c>.</exception>
        public FaultTreeIllustrationPoint(string name,
                                          double beta,
                                          IEnumerable <Stochast> stochasts,
                                          CombinationType combinationType)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (stochasts == null)
            {
                throw new ArgumentNullException(nameof(stochasts));
            }

            Beta            = beta;
            CombinationType = combinationType;
            Name            = name;
            Stochasts       = stochasts;
        }
Ejemplo n.º 16
0
        public void Constructor_ValidArguments_ReturnsExpectedValues(CombinationType combinationType)
        {
            // Setup
            const string name = "Fault tree illustration point name";

            var    random = new Random(21);
            double beta   = random.NextDouble();

            IEnumerable <Stochast> stochasts = Enumerable.Empty <Stochast>();

            // Call
            var illustrationPoint = new FaultTreeIllustrationPoint(name, beta, stochasts, combinationType);

            // Assert
            Assert.IsInstanceOf <IllustrationPointBase>(illustrationPoint);
            Assert.AreEqual(name, illustrationPoint.Name);
            Assert.AreSame(stochasts, illustrationPoint.Stochasts);
            Assert.AreEqual(beta, illustrationPoint.Beta, illustrationPoint.Beta.GetAccuracy());
            Assert.AreEqual(combinationType, illustrationPoint.CombinationType);
        }
Ejemplo n.º 17
0
        public CardSet(int index, Card[] cards, bool isFlush, NumberType[] kickers)
        {
            if (cards.Length != 2 || cards[0].Number > cards[1].Number)
            {
                throw new Exception();
            }

            _cards = cards;
            _index = index;
            Type   = (CombinationType)(FromTable[_index] >> 12);

            if (!isFlush)
            {
                _kicker = new[] { (NumberType)((FromTable[_index] >> 8) & 15), (NumberType)((FromTable[_index] >> 4) & 15), (NumberType)(FromTable[_index] & 15) }
            }
            ;
            else
            {
                IsFlush(kickers);
            }
        }
Ejemplo n.º 18
0
        public static Function Superposition(CombinationType method, params Function[] funcs)
        {
            var from = funcs.Select(func => func.From).Min();
            var to   = funcs.Select(func => func.To).Max();
            Func <double, double> super;

            switch (method)
            {
            case CombinationType.MaxCombination:
                super = x => funcs.Select(func => func.Calculate(x)).Max();
                break;

            case CombinationType.SumCombination:
                super = funcs.Aggregate <Function, Func <double, double> >(z => 0,
                                                                           (acc, func) => y => acc(y) + func.Calculate(y));
                break;

            default:
                return(null);
            }
            return(new Function("SuperPosition", super, from, to));
        }
 public CombinatorialTestAttribute(CombinationType combinationType)
 {
     this.combinationType = combinationType;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Spawns a new SoX process using the specified options in this instance.
        /// </summary>
        /// <param name="inputFiles">Audio files to be processed.</param>
        /// <param name="outputFile">Output file.</param>
        /// <param name="combination">How to combine the input files.</param>
        public void Process(InputFile[] inputFiles, string outputFile, CombinationType combination)
        {
            soxProcess_ = SoxProcess.Create(Path);

            lastError_       = null;
            lastErrorSource_ = null;

            try
            {
                soxProcess_.ErrorDataReceived  += OnSoxProcessOutputReceived;
                soxProcess_.OutputDataReceived += OnSoxProcessOutputReceived;

                List <string> args = new List <string>();

                // Global options.

                if (Buffer.HasValue)
                {
                    args.Add("--buffer " + Buffer.Value);
                }

                if (Multithreaded.HasValue)
                {
                    args.Add(Multithreaded.Value ? "--multi-threaded" : "--single-threaded");
                }

                if (!String.IsNullOrEmpty(CustomArgs))
                {
                    args.Add(CustomArgs);
                }

                switch (combination)
                {
                case CombinationType.Concatenate:
                    args.Add("--combine concatenate");
                    break;

                case CombinationType.Merge:
                    args.Add("--combine merge");
                    break;

                case CombinationType.Mix:
                    args.Add("--combine mix");
                    break;

                case CombinationType.MixPower:
                    args.Add("--combine mix-power");
                    break;

                case CombinationType.Multiply:
                    args.Add("--combine multiply");
                    break;

                case CombinationType.Sequence:
                    args.Add("--combine sequence");
                    break;

                default:
                    // Do nothing.
                    break;
                }

                args.Add("--show-progress");

                // Input options and files.

                if ((inputFiles != null) && (inputFiles.Length > 0))
                {
                    foreach (InputFile inputFile in inputFiles)
                    {
                        args.Add(inputFile.ToString());
                    }
                }
                else
                {
                    args.Add("--null");
                }

                // Output options and file.

                args.Add(Output.ToString());

                if (!string.IsNullOrEmpty(outputFile))
                {
                    if (outputFile.Contains(" "))
                    {
                        if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
                            (Environment.OSVersion.Platform == PlatformID.Win32Windows) ||
                            (Environment.OSVersion.Platform == PlatformID.Win32S) ||
                            (Environment.OSVersion.Platform == PlatformID.WinCE))
                        {
                            args.Add("\"" + outputFile + "\"");
                        }
                        else
                        {
                            args.Add("'" + outputFile + "'");
                        }
                    }
                    else
                    {
                        args.Add(outputFile);
                    }
                }
                else
                {
                    args.Add("--null");
                }

                // Effects.
                foreach (IBaseEffect effect in Effects)
                {
                    args.Add(effect.ToString());
                }

                // Custom effects.
                args.Add(CustomEffects);

                soxProcess_.StartInfo.Arguments = String.Join(" ", args);
                LastCommand = Path + " " + soxProcess_.StartInfo.Arguments;

                try
                {
                    soxProcess_.Start();
                    soxProcess_.BeginOutputReadLine();
                    soxProcess_.BeginErrorReadLine();
                    soxProcess_.WaitForExit();
                }

                catch (Exception ex)
                {
                    throw new SoxException("Cannot spawn SoX process", ex);
                }

                if (!String.IsNullOrEmpty(lastError_))
                {
                    if (String.IsNullOrEmpty(lastErrorSource_))
                    {
                        throw new SoxException(lastError_);
                    }

                    switch (lastErrorSource_)
                    {
                    case "getopt":
                        throw new SoxException("Invalid parameter: " + lastError_);

                    default:
                        throw new SoxException("Processing error: " + lastError_);
                    }
                }
            }

            finally
            {
                if (soxProcess_ != null)
                {
                    soxProcess_.Dispose();
                    soxProcess_ = null;
                }
            }
        }
Ejemplo n.º 21
0
    public static PokerHand Make(CardSet cards)
    {
        cards.Sort();
        var key         = cards [cards.Count - 1];
        var combination = PokerHand.CombinationType.Invalid;

        if (cards.Count > 5)
        {
            if (Dragon.Instance.IsValid(cards, true))
            {
                combination = CombinationType.Dragon;
            }
        }
        else if (cards.Count == 5)
        {
            if (RoyalFlush.Instance.IsValid(cards, true))
            {
                combination = CombinationType.RoyalFlush;
            }
            else if (StraightFlush.Instance.IsValid(cards, true))
            {
                combination = CombinationType.StraightFlush;
            }
            else if (FourOfAKind.Instance.IsValid(cards, true))
            {
                combination = CombinationType.FourOfAKind;
            }
            else if (FullHouse.Instance.IsValid(cards, true))
            {
                combination = CombinationType.FullHouse;
            }
            else if (Flush.Instance.IsValid(cards, true))
            {
                combination = CombinationType.Flush;
            }
            else if (Straight.Instance.IsValid(cards, true))
            {
                combination = CombinationType.Straight;
            }
            else
            {
                combination = CombinationType.Invalid;
            }
        }
        else
        {
            if (Triple.Instance.IsValid(cards, true))
            {
                combination = CombinationType.Triple;
            }
            else if (Pair.Instance.IsValid(cards, true))
            {
                combination = CombinationType.Pair;
            }
            else if (One.Instance.IsValid(cards, true))
            {
                combination = CombinationType.One;
            }
            else
            {
                combination = CombinationType.Invalid;
            }
        }

        return(new PokerHand(new CardSet(cards.ToArray()), key, combination));
    }
Ejemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Combination"/> class.
 /// </summary>
 /// <param name="type">
 /// The rank.
 /// </param>
 /// <param name="cards">
 /// The cards.
 /// </param>
 public Combination(CombinationType type, Card[] cards)
 {
     Type  = type;
     Cards = cards;
 }
Ejemplo n.º 23
0
 public Combination(CombinationType combinationType)
 {
     CombinationType = combinationType;
     Completed       = false;
 }
Ejemplo n.º 24
0
 public CombinationFilter(WaveFilter input1, WaveFilter input2, CombinationType type) : base(input1)
 {
     Input2 = input2;
     Type   = type;
 }
Ejemplo n.º 25
0
 public static IEnumerable<ITuple> ComputeTupleProducts(
     IList<IDomain> domains,
     CombinationType combinationType)
 {
     switch (combinationType)
     {
         case CombinationType.PairWize:
             return Products.PairWize(domains);
         case CombinationType.Cartesian:
             return Products.Cartesian(domains);
         default:
             throw new NotSupportedException(combinationType.ToString());
     }
 }
Ejemplo n.º 26
0
 public PokerHand(CardSet cards, Card key, CombinationType combination)
 {
     this.cards       = cards;
     this.key         = key;
     this.combination = combination;
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Registers the combination which is found to the character.
        /// </summary>
        /// <param name="character"></param>
        /// <param name="power"></param>
        /// <param name="combinationCardsCollection"></param>
        /// <param name="nonCombinationCardsCollection"></param>
        /// <param name="combinationType"></param>
        /// <param name="behaviourPower"></param>
        private void RegisterCombination(ICharacter character, double power, IList<ICard> combinationCardsCollection,
            IList<ICard> nonCombinationCardsCollection, CombinationType combinationType, double behaviourPower)
        {
            IList<ICard> kickersCollection = new List<ICard>();

            if (character.CardsCombination == null || character.CardsCombination.Type < combinationType || character.CardsCombination.Power < power)
            {
                if (combinationCardsCollection.Count < 5)
                {
                    int nonCombinationCardsSize = 5 - combinationCardsCollection.Count;

                    nonCombinationCardsCollection = nonCombinationCardsCollection.OrderByDescending(x => x.Rank).ToList();

                    kickersCollection = nonCombinationCardsCollection.Take(nonCombinationCardsSize).ToList();
                }

                character.CardsCombination = new Combination(power, combinationType, behaviourPower, combinationCardsCollection, kickersCollection);
            }
        }
Ejemplo n.º 28
0
 public CardCombination(CombinationType type, IReadOnlyCollection <Card> cards, double score)
 {
     Type  = type;
     Cards = cards;
     Score = score;
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Spawns a new SoX process using the specified options in this instance and plays the specified files.
 /// </summary>
 /// <param name="inputFiles">Audio files to be played.</param>
 /// <param name="combination">How to combine the input files.</param>
 public void Play(InputFile[] inputFiles, CombinationType combination)
 {
     Process(inputFiles, "--default-device", combination);
 }
Ejemplo n.º 30
0
 public CombinationFilter(WaveFilter input1, WaveFilter input2) : base(input1)
 {
     Input2 = input2;
     Type   = CombinationType.Add;
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Spawns a new SoX process using the specified options in this instance.
 /// </summary>
 /// <param name="inputFile1">First audio file to be processed.</param>
 /// <param name="inputFile2">Second audio file to be processed.</param>
 /// <param name="outputFile">Output file.</param>
 /// <param name="combination">How to combine the input files.</param>
 public void Process(string inputFile1, string inputFile2, string outputFile, CombinationType combination)
 {
     Process(new InputFile[] { new InputFile(inputFile1), new InputFile(inputFile2) }, outputFile, combination);
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Spawns a new SoX process using the specified options in this instance.
 /// </summary>
 /// <param name="inputFile1">First audio file to be processed.</param>
 /// <param name="inputFile2">Second audio file to be processed.</param>
 /// <param name="outputFile">Output file.</param>
 /// <param name="combination">How to combine the input files.</param>
 public void Process(InputFile inputFile1, InputFile inputFile2, string outputFile, CombinationType combination)
 {
     Process(new InputFile[] { inputFile1, inputFile2 }, outputFile, combination);
 }
 public CombinatorialTestAttribute(CombinationType combination)
 {
     this.Combination = combination;
 }
Ejemplo n.º 34
0
        public Dictionary <string, object> Post([FromBody] Dictionary <string, TableJson[]> inputJson, bool exact = true)
        {
            string    playerKey;
            Stopwatch sw = new Stopwatch();

            double[]         playersCount, combinationsCount;
            TableJson[]      args           = inputJson["tables"];
            Table[]          tables         = new Table[args.Length];
            CountJson[]      resultJson     = new CountJson[args.Length];
            ComboCheckJson[] comboCheckJson = new ComboCheckJson[args.Length];

            Func <double, double, string> getCoefficient = (x, overallCount) => (x == 0 ? MAX_COEFFICIENT : Math.Round(overallCount / x * MarginMultiplier, 4)).ToString(nfi);
            Func <int, int, ulong>        C = (pc, cc) => { ulong num = 1; for (int k = 1; k <= 5 - cc; k++)
                                                            {
                                                                num = num * (ulong)(53 - 2 * pc - k - cc) / (ulong)k;
                                                            }
                                                            return(num); };

            sw.Start();
            for (int i = 0; i < args.Length; i++)
            {
                resultJson[i] = new CountJson();

                if (args[i].Players.Length == 0)
                {
                    return new Dictionary <string, object>()
                           {
                               { "timeElapsed", 0 }, { "result", "incorrect request" }
                           }
                }
                ;

                if (args[i].Players[0].Length == 0) // чтение из XML
                {
                    try
                    {
                        TableInfo rt = _tables.Tables.First(ti => ti.Count == args[i].Players.Length);
                        for (int j = 0; j < args[i].Players.Length; j++)
                        {
                            resultJson[i].ExpressCoefficients.Add(string.Format("p{0}{1}", i, j), new Dictionary <string, string>());
                            resultJson[i].PlayersCoefficients.Add(string.Format("p{0}{1}", i, j), Math.Round(rt.Player * MarginMultiplier, 4).ToString(nfi));
                        }
                        foreach (CombinationInfo ct in rt.Combinations)
                        {
                            resultJson[i].CombinationCoefficients.Add(ct.CombinationType, Math.Round(ct.Value * MarginMultiplier, 4).ToString(nfi));
                        }
                        foreach (CombinationInfo ct in rt.ExpressCombinations)
                        {
                            for (int j = 0; j < args[i].Players.Length; j++)
                            {
                                resultJson[i].ExpressCoefficients[string.Format("p{0}{1}", i, j)].Add(ct.CombinationType, Math.Round(ct.Value * MarginMultiplier, 4).ToString(nfi));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(ex);
                        throw;
                    }
                }
                else if (args[i].Common.Length == CardSet.COMMON_CARDS_COUNT) // проверка комбинаций
                {
                    Card[] common = args[i].Common.ToCards();

                    Card[][]  playersCards = args[i].Players.ToCards();
                    CardSet[] sets         = playersCards.Select(p => new CardSet(p.OrderBy(c => c.Number).Union(common).ToArray(), true)).ToArray();
                    Dictionary <int, Card[]> combinations;
                    CombinationType          type = CardSet.GetFinalCombinations(sets, out combinations);
                    comboCheckJson[i] = new ComboCheckJson
                    {
                        Combination         = type.ToString(),
                        PlayersCombinations = combinations.ToDictionary(kvp => string.Format("p{0}{1}", i, kvp.Key), kvp => kvp.Value.Select(c => common.Contains(c) ? Array.IndexOf(common, c) : Array.IndexOf(playersCards[kvp.Key], c) + 5).OrderBy(k => k).ToArray())
                    };
                }
                else // расчет
                {
                    try
                    {
                        tables[i] = new Table(args[i].Players.ToCards(), exact);
                        tables[i].GetProbabilities(args[i].Common.ToCards());
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(System.DateTime.UtcNow);
                        Console.Error.WriteLine(JsonConvert.SerializeObject(inputJson));
                        Console.Error.WriteLine(ex.ToString() + "\r\n(error in calculating counts)");
                        throw;
                    }

                    double overallCount = C(args[i].Players.Length, args[i].Common.Length); //(double)tables[i].Counts.Select(p => p.Sum()).Sum();
                    playersCount      = tables[i].Counts.Select(p => p.Sum()).Take(args[i].Players.Length).ToArray();
                    combinationsCount = tables[i].Counts[args[i].Players.Length];

                    try
                    {
                        for (int j = 0; j < args[i].Players.Length; j++)
                        {
                            playerKey = string.Format("p{0}{1}", i, j);

                            resultJson[i].PlayersCoefficients.Add(playerKey, getCoefficient(playersCount[j], overallCount));
                            for (int k = 0; k < COMBINATIONS_COUNT; k++)
                            {
                                double value = tables[i].Counts[j][k];

                                if (!resultJson[i].ExpressCoefficients.ContainsKey(playerKey))
                                {
                                    resultJson[i].ExpressCoefficients.Add(playerKey, new Dictionary <string, string>());
                                }
                                resultJson[i].ExpressCoefficients[playerKey].Add(((CombinationType)k).ToString(), getCoefficient(value, overallCount));
                            }
                        }

                        for (int k = 0; k < COMBINATIONS_COUNT; k++)
                        {
                            resultJson[i].CombinationCoefficients.Add(((CombinationType)k).ToString(), getCoefficient(combinationsCount[k], overallCount));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(System.DateTime.UtcNow);
                        Console.Error.WriteLine(JsonConvert.SerializeObject(inputJson));
                        Console.Error.WriteLine(ex.ToString() + "\r\n(error in writing coefficients)");
                        throw;
                    }
                }
            }
            int te = (int)sw.ElapsedMilliseconds;

            sw.Stop();

            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            var mode    = exact ? "exact" : "clone";

            return(new Dictionary <string, object>()
            {
                { "timeElapsed", te }, { "version", version }, { "mode", mode }, { "coeffs", resultJson }, { "results", comboCheckJson }
            });
        }
    }
Ejemplo n.º 35
0
 private void CheckProba(CombinationType combinationType, double currentProba, double low, double high)
 {
     Assert.IsTrue(currentProba >= low && currentProba <= high, $"{combinationType.ToString()} : {currentProba} is not betwen {low} and {high}");
 }