Ejemplo n.º 1
0
        /*/// <summary>
         * /// was missilefirecontrol in battlespace.
         * /// </summary>
         * /// <param name="battletick"></param>
         * /// <param name="comSek"></param>
         *
         * public override void firecontrol(int battletick)
         * {
         *  Fix16 locdistance = Trig.distance(comSek.cmbt_loc, comSek.weaponTarget[0].cmbt_loc);
         *  if (locdistance <= comSek.cmbt_vel.Length)//erm, I think? (if we're as close as we're going to get in one tick) could screw up at high velocities.
         *  {
         *      if (!IsReplay)
         *      {
         *          CombatTakeFireEvent evnt = comSek.seekertargethit;
         *          evnt.IsHit = true;
         *          evnt.Tick = battletick;
         *      }
         *      Component launcher = comSek.launcher.weapon;
         *      CombatObject target = comSek.weaponTarget[0];
         *      if (target is ControlledCombatObject)
         *      {
         *          ControlledCombatObject ccTarget = (ControlledCombatObject)target;
         *          var target_icomobj = ccTarget.WorkingObject;
         *          var shot = new Combat.Shot(launcher, target_icomobj, 0);
         *          //defender.TakeDamage(weapon.Template.ComponentTemplate.WeaponInfo.DamageType, shot.Damage, battle);
         *          int damage = shot.Damage;
         *          combatDamage(battletick, target, comSek.launcher, damage, comSek.getDice());
         *          if (target_icomobj.MaxNormalShields < target_icomobj.NormalShields)
         *              target_icomobj.NormalShields = target_icomobj.MaxNormalShields;
         *          if (target_icomobj.MaxPhasedShields < target_icomobj.PhasedShields)
         *              target_icomobj.PhasedShields = target_icomobj.MaxPhasedShields;
         *      }
         *
         *      DeadNodes.Add(comSek);
         *      CombatNodes.Remove(comSek);
         *  }
         *  else if (battletick > comSek.deathTick)
         *  {
         *      DeadNodes.Add(comSek);
         *      CombatNodes.Remove(comSek);
         *  }
         * }
         */

        public override void TakeSpecialDamage(Battle_Space battle, Hit hit, PRNG dice)
        {
            // find out who hit us
            var atkr = battle.FindCombatObject(hit.Shot.Attacker);

            // find out how too
            var dmgType = hit.Shot.DamageType;

            // push/pull effects
            if (atkr.CanPushOrPull(this))
            {
                var deltaV = dmgType.TargetPush.Value * hit.Shot.DamageLeft / 100;
                var vector = atkr.cmbt_loc - this.cmbt_loc;
                if (vector.Length == 0)
                {
                    // pick a random direction to push/pull
                    vector = new Compass(dice.Next(360), false).Point(1);
                }
                vector        /= vector.Length;                                                  // normalize to unit vector
                vector        *= Battle_Space.KilometersPerSquare / Battle_Space.TicksPerSecond; // scale to combat map
                vector        *= deltaV;                                                         // scale to push/pull acceleration factor
                this.cmbt_vel += deltaV;                                                         // apply force
            }

            // teleport effects
            {
                var deltaPos = dmgType.TargetTeleport.Value * hit.Shot.DamageLeft / 100;
                var vector   = new Compass(dice.Next(360), false).Point(deltaPos);
                this.cmbt_loc += deltaPos;                 // apply teleport
            }
        }
        private JobTest StartRandomTest()
        {
            JobTest test;
            var     nr = PRNG.Next(0, 9);

            m_runs[nr]++;
            switch (nr)
            {
            case 0:
            case 1:
            case 2:
            case 3:
                test = new Simple();
                break;

            case 4:
            case 5:
                test = new Wide();
                break;

            case 6:
            case 7:
                test = new WideArg();
                break;

            case 8:
                test = new Delayed();
                break;

            default:
                throw new NotImplementedException();
            }
            test.Timeout = TimeService.Wall + test.Start();
            return(test);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Picks a random element from a weighted sequence.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <returns></returns>
        public static T PickWeighted <T>(this IDictionary <T, double> src, PRNG prng = null)
        {
            var    total = src.Sum(kvp => kvp.Value);
            double num;

            if (prng == null)
            {
                num = RandomHelper.Next(total);
            }
            else
            {
                num = prng.Next(total);
            }
            double sofar = 0;

            foreach (var kvp in src)
            {
                sofar += kvp.Value;
                if (num < sofar)
                {
                    return(kvp.Key);
                }
            }
            return(default(T));            // nothing to pick...
        }
Ejemplo n.º 4
0
    /// <summary>
    /// Generates random nested X.690 node.
    /// </summary>
    /// <param name="branches">Maximum number of branches to use.</param>
    /// <param name="leaves">Maximum number of leaves to use.</param>
    /// <param name="depth">Maximum nessting level.</param>
    /// <param name="lengthEncoding">Definite, indefinite or random.</param>
    /// <returns>Random X.690 node.</returns>
    static public X690.Node RandomBranch(int branches, int leaves, int depth, LengthEncoding lengthEncoding = LengthEncoding.Definite)
    {
        var stack = new Stack <X690.Node>();

        for (int i = 0; i < PRNG.Next(branches + 1); i++)
        {
            stack.Push(RandomBranch(lengthEncoding));
        }
        for (int i = 0; i < PRNG.Next(leaves + 1); i++)
        {
            stack.Push(RandomLeaf(lengthEncoding));
        }
        var root = RandomBranch(lengthEncoding);

        foreach (var node in stack.ToArray().Shuffled())
        {
            root.Nodes.Add(node);
        }
        IEnumerable <X690.Node> target = root.Nodes.Where(i => i.IsConstructed);

        while (--depth > 0)
        {
            foreach (var node in target)
            {
                node.Nodes.Add(RandomBranch(branches, leaves, 0, lengthEncoding));
            }
            target = target.SelectMany(i => i.Nodes.Where(j => j.HasNodes));
        }
        return(root);
    }
Ejemplo n.º 5
0
        public void TestFastDictionary()
        {
            var facit = new Dictionary <int, string>();
            var fast  = new FastDictionary <int, string>();

            for (int r = 0; r < 1000000; r++)
            {
                var rnd = PRNG.Next(0, 13);
                switch (rnd)
                {
                case 0:
                    facit.Clear();
                    fast.Clear();
                    break;

                case 1:
                case 2:
                {
                    // add/change using indexer
                    int key;
                    if (facit.Count > 2 && PRNG.Next(0, 100) < 20)
                    {
                        key = GetRandomKey(facit);
                    }
                    else
                    {
                        key = PRNG.Next(1, 1000);
                    }
                    facit[key] = key.ToString();
                    fast[key]  = key.ToString();
                    break;
                }

                case 3:
                case 4:
                    // add using Add()
                    int b = PRNG.Next(1, 1000);
                    if (facit.ContainsKey(b) == false)
                    {
                        facit.Add(b, b.ToString());
                        fast.Add(b, b.ToString());
                    }
                    break;

                case 5:
                case 6:
                {
                    // add using GetOrInit()
                    int     c      = PRNG.Next(0, 1000);
                    bool    exists = facit.ContainsKey(c);
                    ref var str    = ref fast.GetOrInit(c, out bool wasCreated);
                    Assert.AreEqual(exists, !wasCreated);
                    str = c.ToString();
                    if (!exists)
                    {
                        facit[c] = c.ToString();
                    }
                    break;
                }
Ejemplo n.º 6
0
 public void NextLong()
 {
     for (var i = 0; i < 1000; i++)
     {
         long max = 1234567890;
         Assert.IsFalse(prng.Next(max) > max);
     }
 }
Ejemplo n.º 7
0
        public string CalculateTransactionHash()
        {
            string input =
            Fee.ToString() +
            _permission.GetPermission() +
            nonce.Next(new BigInteger(ulong.MinValue), new BigInteger(ulong.MaxValue)).ToString();

            return StringUtil.ApplyBlake2(input);
        }
        public Point?PlaceStarSystem(Galaxy galaxy, int buffer, Rectangle bounds, int starsLeft, PRNG dice)
        {
            var openPositions = bounds.GetAllPoints();

            foreach (var sspos in galaxy.StarSystemLocations.Select(sspos => sspos.Location))
            {
                openPositions = openPositions.BlockOut(sspos, buffer);
            }
            if (!openPositions.Any())
            {
                return(null);
            }

            // sort positions by distance to nearest star
            var ordered = openPositions.Select(p => new
            {
                Position  = p,
                Distances = galaxy.StarSystemLocations.Select(sspos => sspos.Location.ManhattanDistance(p)).OrderBy(dist => dist)
            }).OrderBy(p => p.Distances.MinOrDefault());
            var minDist = ordered.SelectMany(p => p.Distances).MinOrDefault();

            if (dice.Next(2) == 0)
            {
                // place a star near other stars, but not near TOO many other stars
                var ok = ordered.Where(item => item.Distances.FirstOrDefault() == minDist);
                Dictionary <Point, double> dict;
                if (ok.Any())
                {
                    dict = new Dictionary <Point, double>();
                    foreach (var p in ok)
                    {
                        dict.Add(p.Position, 1d / p.Distances.Sum(d => Math.Pow(d, 3)));
                    }
                }
                else
                {
                    // place a star off in the middle of nowhere
                    dict = new Dictionary <Point, double>();
                    foreach (var p in ordered)
                    {
                        dict.Add(p.Position, p.Distances.Sum(d => Math.Pow(d, 3)));
                    }
                }
                return(dict.PickWeighted(dice));
            }
            else
            {
                // place a star off in the middle of nowhere
                var dict = new Dictionary <Point, double>();
                foreach (var p in ordered)
                {
                    dict.Add(p.Position, p.Distances.Sum(d => Math.Pow(d, 3)));
                }
                return(dict.PickWeighted(dice));
            }
        }
        private void Execute(object ob)
        {
            double ago = TimeService.Wall - m_started;

            Assert.IsTrue(ago > m_delay);
            Assert.IsTrue(ago < m_delay + 0.5);
            Assert.AreEqual(ob, m_name);
            Thread.Sleep(PRNG.Next(0, 4));
            m_didExecute = true;
        }
 private void Execute(object ob)
 {
     // which
     for (int i = 0; i < m_args.Length; i++)
     {
         if (m_args[i] == ob)
         {
             Assert.IsFalse(m_done[i]);
             m_done[i] = true;
         }
     }
     Thread.Sleep(PRNG.Next(0, 4));
 }
Ejemplo n.º 11
0
        public void TestStringUtils()
        {
            Assert.AreEqual(11, StringUtils.HexCharToInteger('B'));

            var cbuf = new char[128];

            var testNumbers = new ulong[]
            {
                0, 1, 2, 100, 1000, 10000, 100000, 10000000,
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000),
                (ulong)PRNG.Next(0, 10000)
            };

            foreach (var val in testNumbers)
            {
                var sans = val.ToString("X");
                var str  = (PRNG.NextBool() ? "0x" : "") + sans;

                Assert.AreEqual(val, StringUtils.FromHex(str));

                var utfBytes = Encoding.UTF8.GetBytes(str);
                Assert.AreEqual(val, StringUtils.FromUTF8Hex(utfBytes));

                var cnt = StringUtils.ToHex(val, cbuf);
                Assert.AreEqual(sans.Length, cnt);
                Assert.IsTrue(sans.AsSpan().SequenceEqual(cbuf.AsSpan(0, cnt)));
            }

            var arr = new byte[64];

            PRNG.NextBytes(arr);

            var facit = BitConverter.ToString(arr).Replace("-", "");
            var my    = StringUtils.ToHex(arr);

            Assert.AreEqual(facit, my);

            var dvalstr = "0.00000000000123";
            var dval    = double.Parse(dvalstr, System.Globalization.CultureInfo.InvariantCulture);
            var lots    = StringUtils.DoubleToString(dval);

            // this is "1.23E-12"
            var defaultToString = dval.ToString(System.Globalization.CultureInfo.InvariantCulture);

            Assert.AreEqual(dvalstr, StringUtils.DoubleToString(dval));
        }
        public override float Start()
        {
            var num = PRNG.Next(1, 5);

            m_args = new object[num];
            m_done = new bool[num];

            for (int i = 0; i < m_args.Length; i++)
            {
                m_args[i] = StringUtils.ToHex(PRNG.NextUInt32());
            }

            JobService.ForEachArgument(m_name, Execute, m_args, OnDone, "onDone");
            return(1.0f);
        }
Ejemplo n.º 13
0
 string GetViewName()
 {
     lock (Views)
     {
         while (true)
         {
             string name = string.Format("view_{0}", PRNG.Next());
             if (!Views.Contains(name))
             {
                 Views.Add(name);
                 return(name);
             }
         }
     }
 }
Ejemplo n.º 14
0
    public static async Task TestTask(ConsoleProgress p)
    {
        var randomDelayValue = PRNG.Next(50, 150);

        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(randomDelayValue);

            p.Dot();
        }
        lock (L1) p.Done("`070`OK!`");
        if (--TasksLeft < 1)
        {
            Semaphore.Release();
        }
    }
Ejemplo n.º 15
0
    /// <summary>
    /// Generates a single random leaf of X.690 node tree.
    /// </summary>
    /// <param name="lengthEncoding">Definite, indefinite or random.</param>
    /// <returns>A tree leaf.</returns>
    static X690.Node RandomLeaf(LengthEncoding lengthEncoding = LengthEncoding.Definite)
    {
        switch (PRNG.Next(0, 4))
        {
        case 0: return(new X690.Null());

        case 1: return(new X690.Boolean(PRNG.NextBool()));

        case 2: return(new X690.Integer(PRNG.Next(int.MinValue, int.MaxValue)));

        case 3: return(new X690.Text(RandomString())
            {
                IsDefiniteLength = lengthEncoding.IsDefiniteLength()
            });
        }
        throw new InvalidOperationException();
    }
Ejemplo n.º 16
0
        public void TestFastList()
        {
            var facit = new List <int>(4);
            var fast  = new FastList <int>();
            var repro = new FastList <int>();

            int[] range      = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int[] smallRange = new int[] { 11, 12, 13 };

            Predicate <int> match = (a) =>
            {
                return(a > 50000);
            };

            // run a million operations
            for (int rounds = 0; rounds < 1000000; rounds++)
            {
                // random operations!
                var op          = PRNG.Next(0, 19);
                int removeIndex = PRNG.Next(0, Math.Max(1, facit.Count));
                var value       = PRNG.Next(0, 100000);
                switch (op)
                {
                case 0:
                    facit.Add(value);
                    fast.Add(value);
                    repro.Add(value);
                    break;

                case 1:
                {
                    facit.Add(value);
                    ref var slot2 = ref fast.Add();
                    slot2 = value;

                    Verify(facit, fast);

                    ref var slot3 = ref repro.Add();
                    slot3 = value;
                    break;
                }
Ejemplo n.º 17
0
        public void TestDataWriter2()
        {
            ulong ss = RandomSeed.GetUInt64();

            byte[] small = new byte[64];

            using (var wrt = new DataWriter(1))
            {
                for (int runs = 0; runs < 10000; runs++)
                {
                    wrt.Clear();
                    var originalSeed = PRNG.NextUInt64(ref ss);

                    var seed = originalSeed;
                    {
                        int numOps = PRNG.Next(ref seed, 1, 15);
                        for (int o = 0; o < numOps; o++)
                        {
                            switch (PRNG.Next(ref seed, 0, 6))
                            {
                            case 0:
                                wrt.WriteBool(PRNG.NextBool(ref seed));
                                break;

                            case 1:
                                wrt.WriteSingle((float)PRNG.Next(ref seed, 1, 100));
                                break;

                            case 2:
                                wrt.WriteVariableInt32(PRNG.Next(ref seed, -50, 50));
                                break;

                            case 3:
                                wrt.WriteString(PRNG.NextUInt32(ref seed).ToString());
                                break;

                            case 4:
                                wrt.WriteUInt16((ushort)PRNG.Next(ref seed, 0, ushort.MaxValue));
                                break;

                            case 5:
                                var sss = small.AsSpan(0, PRNG.Next(ref seed, 1, 25));
                                wrt.WriteBytes(sss);
                                break;
                            }
                        }
                    }

                    // read
                    var rdr = wrt.ReadOnlySpan;

                    seed = originalSeed;
                    {
                        int numOps = PRNG.Next(ref seed, 1, 15);
                        for (int o = 0; o < numOps; o++)
                        {
                            switch (PRNG.Next(ref seed, 0, 6))
                            {
                            case 0:
                            {
                                var facit = PRNG.NextBool(ref seed);
                                Assert.AreEqual(facit, rdr.ReadBool());
                            }
                            break;

                            case 1:
                            {
                                var facit = (float)PRNG.Next(ref seed, 1, 100);
                                Assert.AreEqual(facit, rdr.ReadSingle());
                            }
                            break;

                            case 2:
                            {
                                var facit = PRNG.Next(ref seed, -50, 50);
                                Assert.AreEqual(facit, rdr.ReadVariableInt32());
                            }
                            break;

                            case 3:
                            {
                                var facit = PRNG.NextUInt32(ref seed).ToString();
                                Assert.AreEqual(facit, rdr.ReadString());
                            }
                            break;

                            case 4:
                            {
                                var facit = (ushort)PRNG.Next(ref seed, 0, ushort.MaxValue);
                                Assert.AreEqual(facit, rdr.ReadUInt16());
                            }
                            break;

                            case 5:
                            {
                                var sss = small.AsSpan(0, PRNG.Next(ref seed, 1, 25));
                                var aaa = rdr.ReadBytes(sss.Length);
                                Assert.IsTrue(sss.SequenceEqual(aaa));
                            }
                            break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public void TestPRNG()
        {
            const int iterations = 5000000;

            Console.WriteLine();

            int trues   = 0;
            int larger  = 0;
            int smaller = 0;

            for (int i = 0; i < iterations; i++)
            {
                if (PRNG.NextBool())
                {
                    trues++;
                }
                int val = PRNG.Next(5, 8);                 // 5, 6 or 7
                switch (val)
                {
                case 5:
                    smaller++;
                    break;

                case 6:
                    break;

                case 7:
                    larger++;
                    break;

                default:
                    Assert.Fail("Value " + val + " isn't 5, 6 or 7");
                    break;
                }

                // ranged
                var r1 = (int)PRNG.NextUInt32();
                var r2 = (int)PRNG.NextUInt32();
                if (r1 < r2)
                {
                    var rr = PRNG.Next(r1, r2);
                    Assert.IsTrue(rr >= r1 && rr < r2, rr.ToString() + " is not between " + r1 + " and " + r2);
                }
                else if (r1 > r2)
                {
                    var rr = PRNG.Next(r2, r1);
                    Assert.IsTrue(rr >= r2 && rr < r1, rr.ToString() + " is not between " + r2 + " and " + r1);
                }
            }

            var p = (double)trues / (double)iterations;

            Assert.IsTrue(p > 0.495 && p < 0.505);

            const double third  = 1.0 / 3.0;
            const double offset = third * 0.05;
            const double low    = third - offset;
            const double high   = third + offset;

            p = (double)smaller / (double)iterations;
            Assert.IsTrue(p > low && p < high);

            p = (double)larger / (double)iterations;
            Assert.IsTrue(p > low && p < high);

            // make sure nextdouble() and nextfloat() don't generate numbers outside range
            var state = RandomSeed.GetUInt64();

            for (int r = 0; r < 10000000; r++)
            {
                double d = PRNG.NextDouble(ref state);
                Assert.IsTrue(d >= 0.0 && d < 1.0);

                float f = PRNG.NextFloat(ref state);
                Assert.IsTrue(f >= 0.0f && f < 1.0f);
            }
        }
Ejemplo n.º 19
0
        public void TestPRNG()
        {
            const int iterations = 10000000;

            Console.WriteLine();

            int trues   = 0;
            int larger  = 0;
            int smaller = 0;

            for (int i = 0; i < iterations; i++)
            {
                if (PRNG.NextBool())
                {
                    trues++;
                }
                int val = PRNG.Next(5, 8);                 // 5, 6 or 7
                switch (val)
                {
                case 5:
                    smaller++;
                    break;

                case 6:
                    break;

                case 7:
                    larger++;
                    break;

                default:
                    Assert.Fail("Value " + val + " isn't 5, 6 or 7");
                    break;
                }

                // ranged
                var r1 = (int)PRNG.NextUInt32();
                var r2 = (int)PRNG.NextUInt32();
                if (r1 < r2)
                {
                    var rr = PRNG.Next(r1, r2);
                    Assert.IsTrue(rr >= r1 && rr < r2, rr.ToString() + " is not between " + r1 + " and " + r2);
                }
                else if (r1 > r2)
                {
                    var rr = PRNG.Next(r2, r1);
                    Assert.IsTrue(rr >= r2 && rr < r1, rr.ToString() + " is not between " + r2 + " and " + r1);
                }
            }

            var p = (double)trues / (double)iterations;

            Assert.IsTrue(p > 0.495 && p < 0.505);

            const double third  = 1.0 / 3.0;
            const double offset = third * 0.05;
            const double low    = third - offset;
            const double high   = third + offset;

            p = (double)smaller / (double)iterations;
            Assert.IsTrue(p > low && p < high);

            p = (double)larger / (double)iterations;
            Assert.IsTrue(p > low && p < high);
        }
Ejemplo n.º 20
0
        public override void TakeSpecialDamage(Battle_Space battle, Hit hit, PRNG dice)
        {
            // find out who hit us
            var atkr = battle.FindCombatObject(hit.Shot.Attacker);

            // find out how too
            var dmgType = hit.Shot.DamageType;

            // disrupt reload
            {
                var disrupt = dmgType.DisruptReload.Value * hit.Shot.DamageLeft / 100;
                foreach (var w in Weapons)
                {
                    w.nextReload += disrupt;
                    if (w.nextReload - battle.CurrentTick > w.reloadRate)
                    {
                        w.nextReload = battle.CurrentTick + w.reloadRate;                         // this damage type can't increase past normal reload time
                    }
                }
            }

            // increase reload (doesn't work againts master computers, even disabled ones)
            if (!WorkingVehicle.Components.Any(c => c.HasAbility("Master Computer")))
            {
                var inc = dmgType.IncreaseReload.Value * hit.Shot.DamageLeft / 100;
                foreach (var w in Weapons)
                {
                    w.nextReload += inc;                     // this damage type can increase past normal reload time
                }
            }

            // ship capture
            {
                var cap = dmgType.ShipCapture.Value * hit.Shot.DamageLeft;
                if (cap > WorkingVehicle.GetAbilityValue("Boarding Attack").ToInt() + WorkingVehicle.GetAbilityValue("Boarding Defense").ToInt())
                {
                    // destroy all boarding parties and security stations on the target
                    foreach (var c in WorkingVehicle.Components.Where(c => c.HasAbility("Boarding Attack") || c.HasAbility("Boarding Defense")))
                    {
                        c.Hitpoints = 0;
                    }

                    // see if that killed the target
                    if (battle.CheckForDeath(battle.CurrentTick, this))
                    {
                        return;
                    }

                    // transfer ownership
                    this.WorkingCombatant.Owner = atkr.WorkingObject.Owner;
                }
            }

            // push/pull effects
            if (atkr.CanPushOrPull(this))
            {
                var deltaV = dmgType.TargetPush.Value * hit.Shot.DamageLeft / 100;
                var vector = atkr.cmbt_loc - this.cmbt_loc;
                if (vector.Length == 0)
                {
                    // pick a random direction to push/pull
                    vector = new Compass(dice.Next(360), false).Point(1);
                }
                vector        /= vector.Length;                                                  // normalize to unit vector
                vector        *= Battle_Space.KilometersPerSquare / Battle_Space.TicksPerSecond; // scale to combat map
                vector        *= deltaV;                                                         // scale to push/pull acceleration factor
                this.cmbt_vel += deltaV;                                                         // apply force
            }

            // teleport effects
            {
                var deltaPos = dmgType.TargetTeleport.Value * hit.Shot.DamageLeft / 100;
                var vector   = new Compass(dice.Next(360), false).Point(deltaPos);
                this.cmbt_loc += deltaPos;                 // apply teleport
            }
        }
Ejemplo n.º 21
0
 //[Benchmark]
 public long TestP1() => p1.Next();
 private void Execute(object ob)
 {
     Assert.AreEqual(ob, m_name);
     Thread.Sleep(PRNG.Next(0, 4));
     Interlocked.Increment(ref m_ranTimes);
 }
 private void Execute(object ob)
 {
     Assert.AreEqual(ob, m_name);
     Thread.Sleep(PRNG.Next(0, 4));
     m_didExecute = true;
 }
Ejemplo n.º 24
0
        public void TestBitVector()
        {
            var facit = new bool[9 * 64];

            for (int r = 1; r < 8; r++)
            {
                var sz = r * 64;
                var bv = new BitVector(sz);
                facit.AsSpan().Clear();

                for (int op = 0; op < 10000; op++)
                {
                    var a = PRNG.Next(0, sz);
                    var t = PRNG.Next(0, 14);
                    switch (t)
                    {
                    case 0:
                        bv.Clear();
                        facit.AsSpan().Clear();
                        break;

                    case 1:
                        bv.Set(a, true);
                        facit[a] = true;
                        break;

                    case 2:
                    case 3:
                        bv.Set(a);
                        facit[a] = true;
                        break;

                    case 4:
                    case 5:
                    case 6:
                        bv[a]    = true;
                        facit[a] = true;
                        break;

                    case 7:
                    case 8:
                        bv.Clear(a);
                        facit[a] = false;
                        break;

                    case 9:
                        bv.Set(a, false);
                        facit[a] = false;
                        break;

                    case 10:
                        bv[a]    = false;
                        facit[a] = false;
                        break;

                    case 11:
                    case 12:
                    case 13:
                        bv.Flip(a);
                        if (facit[a])
                        {
                            facit[a] = false;
                        }
                        else
                        {
                            facit[a] = true;
                        }
                        break;
                    }

                    // verify
                    var cnt = 0;
                    for (int i = 0; i < sz; i++)
                    {
                        Assert.AreEqual(facit[i], bv[i]);
                        if (facit[i])
                        {
                            cnt++;
                        }
                    }
                    Assert.AreEqual(cnt, bv.CountSetBits());
                }
            }
        }
Ejemplo n.º 25
0
        public void TestPriorityQueue()
        {
            var queue = new PriorityQueue <int, string>(4);

            queue.Enqueue(5, "five");
            queue.Enqueue(3, "three");
            queue.Enqueue(8, "eight");
            queue.Enqueue(1, "one");
            queue.Enqueue(3, "three-again");

            bool ok = queue.TryDequeue(out var str);

            Assert.IsTrue(ok);
            Assert.AreEqual("one", str);

            ok = queue.TryDequeue(out str);
            Assert.IsTrue(ok);
            Assert.IsTrue(str == "three" || str == "three-again");
            ok = queue.TryDequeue(out str);
            Assert.IsTrue(ok);
            Assert.IsTrue(str == "three" || str == "three-again");

            ok = queue.PeekPriority(out var nextPrio);
            Assert.IsTrue(ok);
            Assert.AreEqual(5, nextPrio);

            ok = queue.TryDequeue(out str);
            Assert.IsTrue(ok);
            Assert.AreEqual("five", str);

            Assert.AreEqual(1, queue.Count);

            queue.Enqueue(6, "six");

            ok = queue.TryDequeue(out str);
            Assert.IsTrue(ok);
            Assert.AreEqual("six", str);

            ok = queue.TryDequeue(out str);
            Assert.IsTrue(ok);
            Assert.AreEqual("eight", str);

            ok = queue.TryDequeue(out str);
            Assert.IsFalse(ok);
            Assert.AreEqual(0, queue.Count);

            queue.Clear();
            queue.Enqueue(3, "3");
            queue.Enqueue(1, "1");
            queue.Enqueue(2, "2");
            ok = queue.Remove("22");
            Assert.IsFalse(ok);
            Assert.AreEqual(3, queue.Count);
            ok = queue.Remove("2");
            Assert.IsTrue(ok);

            Assert.AreEqual("1", queue.Dequeue());
            Assert.AreEqual("3", queue.Dequeue());
            ok = queue.TryDequeue(out _);
            Assert.IsFalse(ok);

            var facit = new List <(int, string)>();

            queue.Clear();
            for (int op = 0; op < 1000000; op++)
            {
                switch (PRNG.Next(0, 8))
                {
                case 0:
                    queue.Clear();
                    facit.Clear();
                    break;

                case 1:
                case 2:
                case 3:
                case 4:
                    // enqueue
                    int add = PRNG.Next(0, 50);
                    queue.Enqueue(add, add.ToString());
                    facit.Add((add, add.ToString()));
                    break;

                case 5:
                    // remove
                    int rem = PRNG.Next(0, 50);
                    var fok = Remove(facit, rem.ToString());
                    var qok = queue.Remove(rem.ToString());
                    Assert.AreEqual(fok, qok);
                    break;

                case 6:
                case 7:
                    // dequeue
                    if (facit.Count <= 0)
                    {
                        continue;
                    }
                    var fitem = Dequeue(facit);
                    var qitem = queue.Dequeue();
                    Assert.AreEqual(fitem, qitem);
                    break;
                }

                Assert.AreEqual(facit.Count, queue.Count);
                if (facit.Count > 0)
                {
                    ok = queue.Peek(out var peekprio, out var peekitem);
                    Assert.IsTrue(ok);
                    Peek(facit, out var facitpeekprio, out var facitpeekitem);

                    Assert.AreEqual(facitpeekprio, peekprio);
                    Assert.AreEqual(facitpeekitem, peekitem);
                }
            }
        }
Ejemplo n.º 26
0
        public void Test7BitEncoding()
        {
            byte[] arr = new byte[1024];

            // test variable lengths
            var numbers = new ulong[7];

            numbers = new ulong[] { 1, 25, 137, 255, 256, 10000, 1000000 };

            ulong state = RandomSeed.GetUInt64();

            for (int runs = 0; runs < 250000; runs++)
            {
                var work = arr.AsSpan();
                for (int i = 0; i < numbers.Length; i++)
                {
                    work.WriteVariableUInt64(numbers[i]);
                }

                int resultLength = arr.Length - work.Length;

                ReadOnlySpan <byte> res = arr.AsSpan(0, resultLength);

                for (int i = 0; i < numbers.Length; i++)
                {
                    var nr = res.ReadVariableUInt64();
                    Assert.AreEqual(numbers[i], nr);
                }

                // re-randomize
                numbers[0] = (ulong)PRNG.Next(ref state, 0, 6);
                numbers[1] = (ulong)PRNG.Next(ref state, 7, 300);
                numbers[2] = (ulong)PRNG.Next(ref state, 300, 5000);
                numbers[3] = (ulong)PRNG.Next(ref state, 5000, 50000);
                numbers[4] = (ulong)PRNG.Next(ref state, 50000, 500000);
                numbers[5] = (ulong)PRNG.NextUInt64(ref state);
                numbers[6] = (ulong)PRNG.NextUInt64(ref state);
            }

            // signed
            var signed = new long[7];

            for (int runs = 0; runs < 250000; runs++)
            {
                // re-randomize
                signed[0] = (long)PRNG.Next(ref state, -5, 5);
                signed[1] = (long)PRNG.Next(ref state, -100, 100);
                signed[2] = (long)PRNG.Next(ref state, -300, 300);
                signed[3] = (long)PRNG.Next(ref state, -5000, 5000);
                signed[4] = (long)PRNG.Next(ref state, -70000, 70000);
                signed[5] = (long)PRNG.NextUInt64(ref state);
                signed[6] = (long)PRNG.NextUInt64(ref state);

                var work = arr.AsSpan();
                for (int i = 0; i < signed.Length; i++)
                {
                    work.WriteVariableInt64(signed[i]);
                }

                int resultLength = arr.Length - work.Length;

                ReadOnlySpan <byte> res = arr.AsSpan(0, resultLength);

                for (int i = 0; i < signed.Length; i++)
                {
                    var nr = res.ReadVariableInt64();
                    Assert.AreEqual(signed[i], nr);
                }
            }
        }
Ejemplo n.º 27
0
 public static void MoreWork(object ob)
 {
     Console.WriteLine("MoreWork(" + ob.ToString() + ")");
     Thread.Sleep(PRNG.Next(2, 5));
 }