예제 #1
0
        protected static bool[] GetVector(CountDictionary primeFactorizationDict, BigInteger maxValue)
        {
            int primeIndex = PrimeFactory.GetIndexFromValue(maxValue);

            bool[] result = new bool[primeIndex];

            if (primeFactorizationDict.Any())
            {
                foreach (KeyValuePair <BigInteger, BigInteger> kvp in primeFactorizationDict)
                {
                    if (kvp.Key > maxValue)
                    {
                        continue;
                    }
                    if (kvp.Key == -1)
                    {
                        continue;
                    }
                    if (kvp.Value % 2 == 0)
                    {
                        continue;
                    }

                    int index = PrimeFactory.GetIndexFromValue(kvp.Key);
                    result[index] = true;
                }
            }

            return(result);
        }
예제 #2
0
 int RawDamageFromParticipatingAttackers(CountDictionary <HealthToken> participatingAttacker)
 {
     return(participatingAttacker.Keys
            .OfType <HealthToken>()
            .Where(x => x.StrifeCount == 0)
            .Select(attacker => cfg.DamageFromAttacker(attacker) * participatingAttacker[attacker]).Sum());
 }
예제 #3
0
 /// <returns>([Key][count]) ordered alphabetically or '[none]' if empty</returns>
 /// <example>1C@3,1E@1,1T@2</example>
 static public string TokenSummary <T>(this CountDictionary <T> dict)
 {
     return(dict.Count == 0 ? "[none]"
                     : dict
            .OrderBy(p => p.Key.ToString())
            .Select(p => p.Value + p.Key.ToString())
            .Join(","));
 }
예제 #4
0
    CountDictionary <HealthToken> GetParticipantCounts(Func <HealthToken, bool> filter)
    {
        var participants = new CountDictionary <HealthToken>();

        foreach (var token in Tokens.Keys.OfType <HealthToken>().Where(filter))
        {
            participants[token] = Math.Max(0, Tokens[token] - cfg.NotParticipating[token]);
        }
        return(participants);
    }
예제 #5
0
    public CountDictionary <K> Clone()
    {
        var clone = new CountDictionary <K>();

        foreach (var invader in Keys)
        {
            clone[invader] = this[invader];
        }
        return(clone);
    }
예제 #6
0
    /// <summary>
    /// Defend has already been applied.
    /// </summary>
    public int GetDamageInflictedByAttackers()
    {
        int rawDamageFromAttackers = RawDamageFromParticipatingAttackers(@event.startingAttackers);

        this.currentAttackers = FromEachStrifed_RemoveOneStrife(@event.startingAttackers);           // does not change start state, modifies gs.Tokens[...] instead

        // Defend
        @event.defend = Tokens.Defend.Count;
        int damageInflictedFromAttackers = Math.Max(rawDamageFromAttackers - @event.defend, 0);

        return(damageInflictedFromAttackers);
    }
예제 #7
0
    /// <summary>
    /// Set-like operation.  Returns a new CountDictionary containing current items less other items
    /// </summary>
    public CountDictionary <K> Except(IDictionary <K, int> other)
    {
        var result = new CountDictionary <K>();

        foreach (var key in this.Keys)
        {
            int missing = this[key] - other[key];
            if (missing > 0)
            {
                result[key] = missing;
            }
        }
        return(result);
    }
예제 #8
0
        public static ulong Solve_SortedSet(ulong[] arr, ulong m)
        {
            // 10000000 - ??? ms

            var sumsLeft = new ulong[arr.Length];

            sumsLeft[0] = arr[0] % m;
            for (var i = 1; i < arr.Length; i++)
            {
                sumsLeft[i] = (sumsLeft[i - 1] + arr[i]) % m;
            }

            var sumsSorted = new SortedSet <ulong>(sumsLeft);
            var sumsCount  = new CountDictionary <ulong>(sumsLeft);

            var max = arr[0] % m;

            for (var i = 0; i < arr.Length; i++)
            {
                var left = i == 0 ? 0ul : sumsLeft[i - 1];

                var searchme = left == 0 ? (m - 1) : (left - 1);

                var searchResult = sumsSorted.GetViewBetween(0, searchme);

                if (searchResult.Count > 0)
                {
                    max = Math.Max(max, (searchResult.Max + m - left) % m);
                }

                var removeMe = sumsLeft[i];

                sumsCount.Decrement(removeMe);

                if (sumsCount.Stat(removeMe) == 0)
                {
                    sumsSorted.Remove(removeMe);
                }
            }

            return(max);
        }
예제 #9
0
    /// <returns>New attacker finvaders</returns>
    CountDictionary <HealthToken> FromEachStrifed_RemoveOneStrife(CountDictionary <HealthToken> participatingInvaders)
    {
        var newAttackers = participatingInvaders.Clone();

        var strifed = participatingInvaders.Keys
                      .OfType <HealthToken>()
                      .Where(x => x.StrifeCount > 0)
                      .OrderBy(x => x.StrifeCount)     // smallest first
                      .ToArray();

        foreach (var orig in strifed)
        {
            // update tracking counts
            int count = Tokens[orig];
            newAttackers[orig] -= count;
            newAttackers[orig.AddStrife(-1)] += count;

            // update real tokens
            Tokens.RemoveStrife(orig, Tokens[orig]);
        }

        return(newAttackers);
    }
예제 #10
0
 static HealthToken PickSmartInvaderToDamage(CountDictionary <HealthToken> participatingInvaders, int availableDamage)
 {
     return(PickItemToKill(participatingInvaders.Keys, availableDamage)
            ?? PickItemToDamage(participatingInvaders.Keys));
 }
예제 #11
0
    public int GetDamageInflictedByDefenders()
    {
        CountDictionary <HealthToken> participants = GetDefenders();

        return(participants.Sum(pair => pair.Key.Class.Attack * pair.Value));
    }
예제 #12
0
 public TokenCountDictionary(Space space, CountDictionary <Token> counts, IIslandTokenApi tokenApi)
 {
     this.Space    = space;
     this.counts   = counts;
     this.tokenApi = tokenApi;
 }
예제 #13
0
파일: MatrixSolve.cs 프로젝트: fengwd/GNFS
        public static void GaussianSolve(CancellationToken cancelToken, GNFS gnfs)
        {
            Serialization.Save.Relations.Smooth.Append(gnfs);             // Persist any relations not already persisted to disk

            // Because some operations clear this collection after persisting unsaved relations (to keep memory usage light)...
            // We completely reload the entire relations collection from disk.
            // This ensure that all the smooth relations are available for the matrix solving step.
            Serialization.Load.Relations.Smooth(ref gnfs);


            List <Relation> smoothRelations = gnfs.CurrentRelationsProgress.SmoothRelations.ToList();

            int smoothCount = smoothRelations.Count;

            BigInteger requiredRelationsCount = gnfs.CurrentRelationsProgress.SmoothRelationsRequiredForMatrixStep;

            gnfs.LogFunction($"Total relations count: {smoothCount}");
            gnfs.LogFunction($"Relations required to proceed: {requiredRelationsCount}");

            while (smoothRelations.Count >= requiredRelationsCount)
            {
                // Randomly select n relations from smoothRelations
                List <Relation> selectedRelations = new List <Relation>();
                while (
                    selectedRelations.Count < requiredRelationsCount
                    ||
                    selectedRelations.Count % 2 != 0                             // Force number of relations to be even
                    )
                {
                    int randomIndex = StaticRandom.Next(0, smoothRelations.Count);
                    selectedRelations.Add(smoothRelations[randomIndex]);
                    smoothRelations.RemoveAt(randomIndex);
                }

                GaussianMatrix gaussianReduction = new GaussianMatrix(gnfs, selectedRelations);
                gaussianReduction.TransposeAppend();
                gaussianReduction.Elimination();

                int number        = 1;
                int solutionCount = gaussianReduction.FreeVariables.Count(b => b) - 1;
                List <List <Relation> > solution = new List <List <Relation> >();
                while (number <= solutionCount)
                {
                    List <Relation> relations = gaussianReduction.GetSolutionSet(number);
                    number++;

                    BigInteger algebraic = relations.Select(rel => rel.AlgebraicNorm).Product();
                    BigInteger rational  = relations.Select(rel => rel.RationalNorm).Product();

                    CountDictionary algCountDict = new CountDictionary();
                    foreach (var rel in relations)
                    {
                        algCountDict.Combine(rel.AlgebraicFactorization);
                    }

                    bool isAlgebraicSquare = algebraic.IsSquare();
                    bool isRationalSquare  = rational.IsSquare();

                    gnfs.LogFunction("---");
                    gnfs.LogFunction($"Relations count: {relations.Count}");
                    gnfs.LogFunction($"(a,b) pairs: {string.Join(" ", relations.Select(rel => $"({rel.A},{rel.B})"))}");
                    gnfs.LogFunction($"Rational  ∏(a+mb): IsSquare? {isRationalSquare} : {rational}");
                    gnfs.LogFunction($"Algebraic ∏ƒ(a/b): IsSquare? {isAlgebraicSquare} : {algebraic}");
                    gnfs.LogFunction($"Algebraic (factorization): {algCountDict.FormatStringAsFactorization()}");

                    if (isAlgebraicSquare && isRationalSquare)
                    {
                        solution.Add(relations);
                        gnfs.CurrentRelationsProgress.AddFreeRelationSolution(relations);
                    }

                    if (cancelToken.IsCancellationRequested)
                    {
                        break;
                    }
                }

                if (cancelToken.IsCancellationRequested)
                {
                    break;
                }
            }
        }