public void QuickSelectTest()
        {
            var r = new Random();

            float[] d = Enumerable.Range(0, 100).Select(i => (float)r.NextDouble()).ToArray();

            var dSorted = new List <float>(d);

            dSorted.Sort();

            int[] indices = Enumerable.Range(0, d.Length).ToArray();
            int   n       = 30;

            QuickSelect.Select(indices, 0, d.Length - 1, n, i => d[i]);

            var selectedD = indices.Select(i => d[i]).ToArray();

            for (int i = 0; i < n; i++)
            {
                Assert.IsTrue(selectedD[i] < selectedD[n]);
            }

            float limit = d[indices[n]];

            Assert.AreEqual(30, d.Count(x => x < limit));
        }
Пример #2
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //TODO  Make it so that ListBox updates itself with the new logs
            if (lbLogs.Items.Count > 0)
            {

                List<String> logTypes = lbLogs.Items.Cast<String>().ToList();

                string quickSelectName = "";

                MessageTextBox popup = new MessageTextBox();
                popup.Text = "Enter Name For Log Set";
                popup.inputLabel.Text = "Name";
                popup.ShowDialog();

                quickSelectName = popup.Results;

                if (quickSelectName != "")
                {
                    QuickSelect qs = new QuickSelect(quickSelectName, logTypes);
                    qs.WriteToConfig();
                    _mainForm.AddQuickSelect(qs);
                }
            }
            else
            {
                MessageBox.Show("Please enter some log types for the set separated by commas.\r\nFor example: ip,notifier,SIPEngine");
            }
        }
Пример #3
0
        public void UnsortedArrayUnevenLength()
        {
            var sut   = new QuickSelect();
            var input = new[] { 3, 1, 7, 10, 2, 5, 9, 4, 8, 6 };

            Assert.Equal(8, sut.GetLargestElement(input, 7));
        }
Пример #4
0
        public void FindSmallestElementInSingleElementArray()
        {
            var sut   = new QuickSelect();
            var input = new[] { 1 };

            Assert.Equal(1, sut.GetLargestElement(input, 0));
        }
Пример #5
0
        public void SortedArray()
        {
            var sut   = new QuickSelect();
            var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            Assert.Equal(8, sut.GetLargestElement(input, 7));
        }
Пример #6
0
        public void Test2()
        {
            var random = new Random();

            for (int j = 0; j < 100; j++)
            {
                var randomSource = Enumerable.Range(0, 200).Select(_ => random.NextDouble() * 50).ToArray();

                var pool = ArrayPool <int> .Shared.Rent(randomSource.Length);

                var indices = pool.AsSpan(0, randomSource.Length);
                int n       = random.Next(200);

                QuickSelect.Iota(indices);
                QuickSelect.Execute(randomSource, indices, n);

                var pivot = randomSource[indices[n]];
                for (int i = 0; i < n; i++)
                {
                    var result = Comparer <double> .Default.Compare(randomSource[indices[i]], pivot);

                    Assert.IsTrue(result < 0);
                }


                for (int i = n; i < randomSource.Length; i++)
                {
                    var result = Comparer <double> .Default.Compare(randomSource[indices[i]], pivot);

                    Assert.IsTrue(0 <= result);
                }

                ArrayPool <int> .Shared.Return(pool);
            }
        }
Пример #7
0
        public static void Main()
        {
            int[]       arr    = new int[] { 62, 43, 54, 16, 84, 27, 93, 75, 377, 120 };
            QuickSelect alg    = new QuickSelect(arr, 3);
            int         result = alg.FindIndex(0, arr.Length - 1);

            Console.WriteLine("result is {0}", result);
        }
Пример #8
0
 public void SelectWithComparerTest_KLessThan0()
 {
     Point[] points = new Point[10];
     for (int i = 0; i < 10; i++)
     {
         points[i] = new Point(i, 10 - i);
     }
     QuickSelect.Select(points, Point.X_ORDER, -1);
 }
Пример #9
0
 public void SelectWithComparerTest_KGreaterOrEqualThanN()
 {
     Point[] points = new Point[10];
     for (int i = 0; i < 10; i++)
     {
         points[i] = new Point(i, 10 - i);
     }
     QuickSelect.Select(points, Point.X_ORDER, 10);
 }
Пример #10
0
        public static void Test()
        {
            var obj = new QuickSelect();

//            int[] array = new[] {5, 9, 1, 7, 2, 4, 5};
            int[] array = new[] { 1, 9, 1, 20, 2, 3, 2 };
            obj.DoSelect(array, 0, array.Length - 1, array.Length / 2);
            Utils.DumpArray(array);
        }
Пример #11
0
        public void testSelectK()
        {
            var a = new[]
            {
                1, 3, 5, 2, 4, 6, 0
            };

            Assert.Equal(3, QuickSelect.Select(a, 3, (a1, b) => a1 - b));
        }
Пример #12
0
        public void SelectWithComparerTest_NullComparer()
        {
            Point[] points = new Point[10];
            for (int i = 0; i < 10; i++)
            {
                points[i] = new Point(i, 10 - i);
            }

            QuickSelect.Select(points, null, 1);
        }
Пример #13
0
        public void QuickSelectTest()
        {
            var arrOrigin = TestData.NewUnsortedArray;
            var arr       = TestData.NewUnsortedArray;

            Assert.IsTrue(arr.SequenceEqual(arrOrigin));
            int k        = new Random().Next(arr.Length);
            var selected = new QuickSelect().Select(arr, k);

            new QuickSort().Sort(arrOrigin);
            Assert.AreEqual(selected, arrOrigin[k]);
        }
Пример #14
0
        public void Test7()
        {
            ReadOnlySpan <int> randomSource = Enumerable.Range(0, 200).Shuffle().ToArray().AsSpan();
            var pool = ArrayPool <int> .Shared.Rent(randomSource.Length);

            var indices = pool.AsSpan(0, randomSource.Length);

            QuickSelect.Iota(indices);

            //Get 50 <= item < 60
            int n = 50;

            QuickSelect.Execute(randomSource, indices, 50);
            QuickSelect.Execute(randomSource, indices[50..], 10);
Пример #15
0
        public void SelectTest()
        {
            String[] a = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            Shuffle.Do(a);

            String v = QuickSelect.Select(a, 3) as String;

            Assert.IsNotNull(v);
            Assert.AreEqual("3", v);
            for (int i = 0; i < 3; i++)
            {
                Assert.IsTrue(SortHelper.Less(a[i], v));
            }
            Assert.AreEqual(a[3], v);
        }
        public void QuickSelect_Test()
        {
            var nodeCount = 10000;

            var rnd           = new Random();
            var randomNumbers = Enumerable.Range(1, nodeCount)
                                .OrderBy(x => rnd.Next())
                                .ToArray();

            var k = rnd.Next(1, nodeCount);

            var expected = k;
            var actual   = QuickSelect <int> .FindSmallest(randomNumbers, k);

            Assert.AreEqual(actual, expected);
        }
Пример #17
0
        public void Test2_3()
        {
            var random = new Random();

            for (int k = 0; k < 100; k++)
            {
                ReadOnlySpan <double> randomSource =
                    Enumerable.Range(0, 200).Select(_ => random.NextDouble() * 50).ToArray().AsSpan();
                var pool = ArrayPool <int> .Shared.Rent(randomSource.Length);

                var indices = pool.AsSpan(0, randomSource.Length);

                QuickSelect.Iota(indices);

                int prevN = 0;

                for (int j = 0; j < 2; j++)
                {
                    var tmpIndices = indices.Slice(prevN, indices.Length - prevN);
                    int n          = random.Next(tmpIndices.Length);

                    QuickSelect.Execute(randomSource, tmpIndices, n);

                    var pivot = randomSource[tmpIndices[n]];
                    for (int i = 0; i < n; i++)
                    {
                        var result = Comparer <double> .Default.Compare(randomSource[tmpIndices[i]], pivot);

                        Assert.IsTrue(result <= 0);
                    }

                    for (int i = n; i < tmpIndices.Length; i++)
                    {
                        var result = Comparer <double> .Default.Compare(randomSource[tmpIndices[i]], pivot);

                        Assert.IsTrue(0 <= result);
                    }

                    prevN = n + prevN;
                }

                ArrayPool <int> .Shared.Return(pool);
            }
        }
Пример #18
0
        public void Fuzzy()
        {
            var       sut         = new QuickSelect();
            var       random      = new Random();
            const int inputLength = 1000;
            var       input       = new int[inputLength];

            for (var i = 0; i < inputLength; i++)
            {
                input[i] = random.Next(inputLength * 10);
            }

            var sorted = input.OrderBy(arg => arg).ToArray();

            for (var i = 0; i < inputLength; i++)
            {
                Assert.Equal(sorted[i], sut.GetLargestElement(input, i));
            }
        }
Пример #19
0
        public void Test4()
        {
            var random = new Random();


            //var randomSource = new int[] { 1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8 };
            Span <int> randomSource = new int[] { 4, 4, 8, 1, 2, 5, 4, 4, 4, 6, 7, 3 }.AsSpan();

            var pool = ArrayPool <int> .Shared.Rent(randomSource.Length);

            var indices = pool.AsSpan(0, randomSource.Length);
            //int n = random.Next(randomSource.Length);
            int n = 6;

            QuickSelect.Iota(indices);
            QuickSelect.Execute <int>(randomSource, indices, n);
            //or
            //QuickSelect.Execute((ReadOnlySpan<int>)randomSource, indices, n);
            //or
            //QuickSelect.Execute(randomSource, indices, n, Comparer<int>.Default);

            DebugView <int>(randomSource, indices, n);

            var pivot = randomSource[indices[n]];

            for (int i = 0; i < n; i++)
            {
                var result = Comparer <double> .Default.Compare(randomSource[indices[i]], pivot);

                Assert.IsTrue(result <= 0);
            }


            for (int i = n + 1; i < randomSource.Length; i++)
            {
                var result = Comparer <double> .Default.Compare(randomSource[indices[i]], pivot);

                Assert.IsTrue(0 <= result);
            }

            ArrayPool <int> .Shared.Return(pool);
        }
Пример #20
0
        public void SelectWithComparerTest()
        {
            Point[] points = new Point[10];
            for (int i = 0; i < 10; i++)
            {
                points[i] = new Point(i, 10 - i);
            }
            Shuffle.Do(points);

            Point v = QuickSelect.Select(points, Point.X_ORDER, 3) as Point;

            Assert.IsNotNull(v);
            Assert.AreEqual(3, v.X);
            Assert.AreEqual(7, v.Y);
            for (int i = 0; i < 3; i++)
            {
                Assert.IsTrue(SortHelper.Less(Point.X_ORDER, points[i], v));
            }
            Assert.AreEqual(points[3], v);
        }
Пример #21
0
        /// <summary>
        /// Update the rotation forces.
        /// </summary>
        public override void UpdateRotation()
        {
            var updateNormalRotation = m_Stopping;
            var targetNormal         = m_Stopping ? (m_StopGravityDirection.sqrMagnitude > 0 ? -m_StopGravityDirection : -m_CharacterLocomotion.GravityDirection) : m_CharacterLocomotion.Up;

            if (!m_Stopping)
            {
                // If the depth offset isn't zero then use two raycasts to determine the ground normal. This will allow a long character (such as a horse) to correctly
                // adjust to a slope.
                if (m_DepthOffset != 0)
                {
                    var        frontPoint = m_Transform.position;
                    bool       frontHit;
                    RaycastHit raycastHit;
                    if ((frontHit = Physics.Raycast(m_Transform.TransformPoint(0, m_CharacterLocomotion.Radius, m_DepthOffset * Mathf.Sign(m_CharacterLocomotion.InputVector.y)),
                                                    -m_CharacterLocomotion.Up, out raycastHit, m_Distance + m_CharacterLocomotion.Radius, m_CharacterLayerManager.SolidObjectLayers, QueryTriggerInteraction.Ignore)))
                    {
                        frontPoint   = raycastHit.point;
                        targetNormal = raycastHit.normal;
                    }

                    if (Physics.Raycast(m_Transform.TransformPoint(0, m_CharacterLocomotion.Radius, m_DepthOffset * -Mathf.Sign(m_CharacterLocomotion.InputVector.y)),
                                        -m_CharacterLocomotion.Up, out raycastHit, m_Distance + m_CharacterLocomotion.Radius, m_CharacterLayerManager.SolidObjectLayers, QueryTriggerInteraction.Ignore))
                    {
                        if (frontHit)
                        {
                            if (m_NormalizeDirection)
                            {
                                var backPoint = raycastHit.point;
                                var direction = (frontPoint - backPoint).normalized;
                                targetNormal = Vector3.Cross(direction, Vector3.Cross(m_CharacterLocomotion.Up, direction)).normalized;
                            }
                            else
                            {
                                targetNormal = (targetNormal + raycastHit.normal).normalized;
                            }
                        }
                        else
                        {
                            targetNormal = raycastHit.normal;
                        }
                    }

                    m_CharacterLocomotion.GravityDirection = -targetNormal;
                    updateNormalRotation = true;
                }
                else
                {
                    var hitCount = m_CharacterLocomotion.Cast(-m_CharacterLocomotion.Up * m_Distance,
                                                              m_CharacterLocomotion.PlatformMovement + m_CharacterLocomotion.Up * m_CharacterLocomotion.ColliderSpacing, ref m_CombinedRaycastHits, ref m_ColliderIndexMap);

                    // The character hit the ground if any hit points are below the collider.
                    for (int i = 0; i < hitCount; ++i)
                    {
                        var closestRaycastHit = QuickSelect.SmallestK(m_CombinedRaycastHits, hitCount, i, m_RaycastHitComparer);

                        // The hit point has to be under the collider for the character to align to it.
                        var activeCollider = m_CharacterLocomotion.ColliderCount > 1 ? m_CharacterLocomotion.Colliders[m_ColliderIndexMap[closestRaycastHit]] : m_CharacterLocomotion.Colliders[0];
                        if (!MathUtility.IsUnderCollider(m_Transform, activeCollider, closestRaycastHit.point))
                        {
                            continue;
                        }

                        targetNormal         = m_CharacterLocomotion.GravityDirection = -closestRaycastHit.normal;
                        updateNormalRotation = true;
                        break;
                    }
                }
            }

            // The rotation is affected by aligning to the ground or having a different up rotation from gravity.
            if (updateNormalRotation)
            {
                Rotate(targetNormal);
            }
        }
Пример #22
0
        /// <summary>
        /// Determine any targets that are within the crosshairs raycast.
        /// </summary>
        private void Update()
        {
            var       crosshairsColor = m_DefaultColor;
            var       crosshairsRay   = m_Camera.ScreenPointToRay(m_CenterRectTransform.position);
            Transform target          = null;

            // Prevent the ray between the character and the camera from causing a false collision.
            if (!m_CharacterLocomotion.FirstPersonPerspective)
            {
                var direction = m_CharacterTransform.InverseTransformPoint(crosshairsRay.origin);
                direction.y          = 0;
                crosshairsRay.origin = crosshairsRay.GetPoint(direction.magnitude);
            }
            var hitCount = Physics.SphereCastNonAlloc(crosshairsRay, m_CollisionRadius, m_RaycastHits, m_CameraController.LookDirectionDistance, m_CharacterLayerManager.IgnoreInvisibleLayers, QueryTriggerInteraction.Ignore);

#if UNITY_EDITOR
            if (hitCount == m_MaxCollisionCount)
            {
                Debug.LogWarning("Warning: The crosshairs detected the maximum number of objects. Consider increasing the Max Collision Count on the Crosshairs Monitor.");
            }
#endif
            if (hitCount > 0)
            {
                for (int i = 0; i < hitCount; ++i)
                {
                    var closestRaycastHit          = QuickSelect.SmallestK(m_RaycastHits, hitCount, i, m_RaycastHitComparer);
                    var closestRaycastHitTransform = closestRaycastHit.transform;
                    // The crosshairs cannot hit the character that is attached to the camera.
                    if (closestRaycastHitTransform.IsChildOf(m_CharacterTransform))
                    {
                        continue;
                    }

                    if (MathUtility.InLayerMask(closestRaycastHitTransform.gameObject.layer, m_CharacterLayerManager.EnemyLayers))
                    {
                        target          = closestRaycastHitTransform;
                        crosshairsColor = m_TargetColor;
                    }
                    break;
                }
            }
            if (m_AimAssist != null)
            {
                m_AimAssist.SetTarget(target);
            }

            if (m_EquippedItem != null)
            {
                m_CurrentCrosshairsSpread = Mathf.SmoothDamp(m_CurrentCrosshairsSpread, m_TargetCrosshairsSpread, ref m_CrosshairsSpreadVelocity,
                                                             m_EquippedItem.QuadrantSpreadDamping);
            }
            m_CenterCrosshairsImage.color = crosshairsColor;
            if (m_LeftCrosshairsImage != null && m_LeftCrosshairsImage.enabled)
            {
                m_LeftCrosshairsImage.color = crosshairsColor;
                PositionSprite(m_LeftRectTransform, -m_EquippedItem.QuadrantOffset - m_CurrentCrosshairsSpread, 0);
            }
            if (m_TopCrosshairsImage != null && m_TopCrosshairsImage.enabled)
            {
                m_TopCrosshairsImage.color = crosshairsColor;
                PositionSprite(m_TopRectTransform, 0, m_EquippedItem.QuadrantOffset + m_CurrentCrosshairsSpread);
            }
            if (m_RightCrosshairsImage != null && m_RightCrosshairsImage.enabled)
            {
                m_RightCrosshairsImage.color = crosshairsColor;
                PositionSprite(m_RightRectTransform, m_EquippedItem.QuadrantOffset + m_CurrentCrosshairsSpread, 0);
            }
            if (m_BottomCrosshairsImage != null && m_BottomCrosshairsImage.enabled)
            {
                m_BottomCrosshairsImage.color = crosshairsColor;
                PositionSprite(m_BottomRectTransform, 0, -m_EquippedItem.QuadrantOffset - m_CurrentCrosshairsSpread);
            }

            var enableImage = !m_Aiming || (m_EquippedItem != null && m_EquippedItem.ShowCrosshairsOnAim);
            if (enableImage != m_EnableImage)
            {
                m_EnableImage = enableImage;
                EnableCrosshairsImage(enableImage);
            }
        }
Пример #23
0
 public int FindKthLargest(int[] nums, int k)
 {
     return(QuickSelect.Select(nums, 0, nums.Length - 1, nums.Length - k + 1));
 }
Пример #24
0
 public void SelectWithComparerTest_NullArray()
 {
     QuickSelect.Select(null, Point.X_ORDER, 1);
 }
Пример #25
0
 public void SelectTest_KGreaterOrEqualThanN()
 {
     String[] a = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
     QuickSelect.Select(a, 10);
 }
Пример #26
0
 public void SelectTest_KLessThan0()
 {
     String[] a = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
     QuickSelect.Select(a, -1);
 }
Пример #27
0
 public void SelectTest_NullArray()
 {
     QuickSelect.Select(null, 1);
 }
Пример #28
0
        /// <summary>
        /// The object has taken been damaged.
        /// </summary>
        /// <param name="amount">The amount of damage taken.</param>
        /// <param name="position">The position of the damage.</param>
        /// <param name="direction">The direction that the object took damage from.</param>
        /// <param name="forceMagnitude">The magnitude of the force that is applied to the object.</param>
        /// <param name="frames">The number of frames to add the force to.</param>
        /// <param name="radius">The radius of the explosive damage. If 0 then a non-explosive force will be used.</param>
        /// <param name="attacker">The GameObject that did the damage.</param>
        /// <param name="attackerObject">The object that did the damage.</param>
        /// <param name="hitCollider">The Collider that was hit.</param>
        public virtual void OnDamage(float amount, Vector3 position, Vector3 direction, float forceMagnitude, int frames, float radius, GameObject attacker, object attackerObject, Collider hitCollider)
        {
#if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER
            if (m_NetworkInfo != null && m_NetworkInfo.IsLocalPlayer())
            {
                m_NetworkHealthMonitor.OnDamage(amount, position, direction, forceMagnitude, frames, radius, attacker, hitCollider);
            }
#endif

            // Add a multiplier if a particular collider was hit. Do not apply a multiplier if the damage is applied through a radius because multiple
            // collider are hit.
            if (radius == 0 && direction != Vector3.zero && hitCollider != null)
            {
                Hitbox hitbox;
                if (m_ColliderHitboxMap != null && m_ColliderHitboxMap.Count > 0)
                {
                    if (m_ColliderHitboxMap.TryGetValue(hitCollider, out hitbox))
                    {
                        amount *= hitbox.DamageMultiplier;
                    }
                    else
                    {
                        // The main collider may be overlapping child hitbox colliders. Perform one more raycast to ensure a hitbox collider shouldn't be hit.
                        float distance = 0.2f;
                        if (hitCollider is CapsuleCollider)
                        {
                            distance = (hitCollider as CapsuleCollider).radius;
                        }
                        else if (hitCollider is SphereCollider)
                        {
                            distance = (hitCollider as SphereCollider).radius;
                        }

                        // The hitbox collider may be underneath the base collider. Fire a raycast to detemine if there are any colliders underneath the hit collider
                        // that should apply a multiplier.
                        var hitCount = Physics.RaycastNonAlloc(position, direction, m_RaycastHits, distance,
                                                               ~(1 << LayerManager.IgnoreRaycast | 1 << LayerManager.Overlay | 1 << LayerManager.VisualEffect), QueryTriggerInteraction.Ignore);
                        for (int i = 0; i < hitCount; ++i)
                        {
                            var closestRaycastHit = QuickSelect.SmallestK(m_RaycastHits, hitCount, i, m_RaycastHitComparer);
                            if (closestRaycastHit.collider == hitCollider)
                            {
                                continue;
                            }
                            // A new collider has been found - stop iterating if the hitbox map exists and use the hitbox multiplier.
                            if (m_ColliderHitboxMap.TryGetValue(closestRaycastHit.collider, out hitbox))
                            {
                                amount     *= hitbox.DamageMultiplier;
                                hitCollider = hitbox.Collider;
                                break;
                            }
                        }
                    }
                }
            }

            // Apply the damage to the shield first because the shield can regenrate.
            if (m_ShieldAttribute != null && m_ShieldAttribute.Value > m_ShieldAttribute.MinValue)
            {
                var shieldAmount = Mathf.Min(amount, m_ShieldAttribute.Value - m_ShieldAttribute.MinValue);
                amount -= shieldAmount;
                m_ShieldAttribute.Value -= shieldAmount;
            }

            // Decrement the health by remaining amount after the shield has taken damage.
            if (m_HealthAttribute != null && m_HealthAttribute.Value > m_HealthAttribute.MinValue)
            {
                m_HealthAttribute.Value -= Mathf.Min(amount, m_HealthAttribute.Value - m_HealthAttribute.MinValue);
            }

            var force = direction * forceMagnitude;
            if (forceMagnitude > 0)
            {
                // Apply a force to the object.
                if (m_ForceObject != null)
                {
                    m_ForceObject.AddForce(force, frames);
                }
                else
                {
                    // Apply a force to the rigidbody if the object isn't a character.
                    if (m_Rigidbody != null && !m_Rigidbody.isKinematic)
                    {
                        if (radius == 0)
                        {
                            m_Rigidbody.AddForceAtPosition(force * MathUtility.RigidbodyForceMultiplier, position);
                        }
                        else
                        {
                            m_Rigidbody.AddExplosionForce(force.magnitude * MathUtility.RigidbodyForceMultiplier, position, radius);
                        }
                    }
                }
            }

            // Let other interested objects know that the object took damage.
            EventHandler.ExecuteEvent <float, Vector3, Vector3, GameObject, Collider>(m_GameObject, "OnHealthDamage", amount, position, force, attacker, hitCollider);
            if (m_OnDamageEvent != null)
            {
                m_OnDamageEvent.Invoke(amount, position, force, attacker);
            }

            // The object is dead when there is no more health or shield.
            if (!IsAlive())
            {
#if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER
                if (m_NetworkInfo == null || m_NetworkInfo.IsLocalPlayer())
                {
#endif
                Die(position, force, attacker);
#if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER
            }
#endif
            }
            else
            {
                // Play any take damage audio if the object did not die. If the object died then the death audio will play.
                m_TakeDamageAudioClipSet.PlayAudioClip(m_GameObject);
            }
        }
        public static PageDurationDistributionHistogram FromDistribution(int[] distribution)
        {
            if (distribution.Length == 0)
            {
                return(PageDurationDistributionHistogram.Empty);
            }
            var _99 = new QuickSelect().Select(distribution, 0.99);

            //var _99 = data[(int)(data.Length*0.99)].Duration;

            var bucketSize = (int)Math.Ceiling(_99 / (double)BucketCount);

            if (bucketSize == 0)            //this happens when distribution contains only 0 values, which occaisonally happens for static content
            {
                bucketSize = 1;
            }


            var buckets = Enumerable.Range(0, BucketCount).Select(i => new PageDurationDistributionHistogram.Bucket {
                Count = 0, MinIncl = i * bucketSize, MaxExcl = (i + 1) * bucketSize
            }).ToArray();

            Func <int, int> getBucketIndex = d => (int)(d / (double)bucketSize);

            foreach (var row in distribution)
            {
                var idx = getBucketIndex(row);
                if (idx >= buckets.Length)
                {
                    continue;
                }
                buckets[idx].Count++;
            }

            var total = distribution.Length;
            var sum   = 0;

            int?medianBucketIndex = null;
            int?_90pctBucketIndex = null;
            int?meanBucketIndex   = null;

            var avg = (int)distribution.Average();
            var ct  = 0;

            foreach (var bucket in buckets)
            {
                sum += bucket.Count;
                bucket.CumulativePercentage = (int)(100.0 * sum / (double)total);
                if (medianBucketIndex == null && bucket.CumulativePercentage >= 50)
                {
                    medianBucketIndex = ct;
                }

                if (_90pctBucketIndex == null && bucket.CumulativePercentage >= 90)
                {
                    _90pctBucketIndex = ct;
                }

                if (meanBucketIndex == null && bucket.MinIncl >= avg)
                {
                    meanBucketIndex = ct;
                }

                ct++;
            }

            return(new PageDurationDistributionHistogram(buckets, meanBucketIndex ?? 0, medianBucketIndex ?? 0, _90pctBucketIndex ?? 0));
        }
Пример #30
0
        static void Main(string[] args)
        {
            var fourthLargest = QuickSelect.FindKthLargest(new int[] { -10, 2, 1, 9, -6, 44, 0, 3, -17, 8 }, 4);

            int[][] people = new int[][] { new int[] { 7, 0 }, new int[] { 4, 4 }, new int[] { 7, 1 },
                                           new int[] { 5, 0 }, new int[] { 6, 1 }, new int[] { 5, 2 } };

            Array.Sort(people, (a, b) => {
                if (a[0] > b[0])
                {
                    return(1);
                }
                else if (a[0] < b[0])
                {
                    return(-1);
                }
                else
                {
                    return(0);
                }
            });

            var sorted = people.OrderByDescending(i => i[0]).ThenBy(i => i[1]).ToArray();
            SortedList <int, int> sortedList = new SortedList <int, int>();
            HashSet <int>         map        = new HashSet <int>();
            StringBuilder         sb         = new StringBuilder("Hello");

            for (int i = 0; i < sb.Length; i++)
            {
                if (sb[i] >= 65 && sb[i] <= 90)
                {
                    sb[i] = (char)(sb[i] + 32);
                }
            }
            int[] arrayForSort = new int[] { -10, 2, 1, 9, -6, 44, 0, 3, -17, 8 };
            BubleSort.Sort(arrayForSort, false);
            int[] nums2  = new int[] { 0, 1, 2, 4, 5, 6, 7, 9 };
            var   binRes = binarySearch(nums2, 0, nums2.Length - 1, 0);

            List <int> list  = new List <int>(new int[] { 1, 3, 5, 7, 9 });
            var        biRes = list.BinarySearch(4);

            int[] nums = new int[] { 3, 0, 1 };
            (new missing_number()).MissingNumber(nums);


            int seed = 0;
            var xor  = nums.Aggregate(seed++, (x, y) => x ^ y);

            xor = Enumerable.Range(1, 4).Aggregate((x, y) => x ^ y);

            (new Swapping_two_integer_variables_without_an_intermediary_variable()).swapArray(nums, 0, 2);
            ListNode head = new ListNode(0);
            ListNode pre  = head;

            for (int i = 1; i < 10; i++)
            {
                ListNode tmp = new ListNode(i);
                pre.next = tmp;
                pre      = pre.next;
            }
            var bst = (new convert_sorted_list_to_binary_search_treeV2()).SortedListToBST(head);

            LeetCode.TreeNode node   = new LeetCode.TreeNode(1);
            LeetCode.TreeNode node1  = new LeetCode.TreeNode(2);
            LeetCode.TreeNode node12 = new LeetCode.TreeNode(5);
            node.left  = node1;
            node.right = node12;
            LeetCode.TreeNode node21 = new LeetCode.TreeNode(3);
            LeetCode.TreeNode node22 = new LeetCode.TreeNode(4);
            node1.left  = node21;
            node1.right = node22;
            LeetCode.TreeNode node31 = new LeetCode.TreeNode(6);
            node12.right = node31;

            (new flatten_binary_tree_to_linked_list()).Flatten(node);

            (new construct_binary_tree_from_preorder_and_inorder_traversalV2()).BuildTree(
                new int[] { 3, 9, 20, 15, 7 },
                new int[] { 9, 3, 15, 20, 7 }
                );

            IList <IList <int> > result2 = new List <IList <int> >();

            result2.Add(new int[] { 1, 2, 3 }.Concat(new int[] { 4, 5, 6 }).ToArray());
            List <int[]> _matrix = new List <int[]>();

            _matrix.Add(new int[] { 1, 2, 0, 4 });
            _matrix.Add(new int[] { 5, 6, 7, 8 });
            _matrix.Add(new int[] { 9, 10, 11, 12 });

            var matrix = _matrix.ToArray();

            var row1 = matrix[0];
            var bol  = Enumerable.Any(row1, i => i == 0);

            for (int i = 0; i < 4; i++)
            {
                matrix[0][i] = 0;
            }

            //int n = 3;
            //int[][] matrix = new int[n][];
            //for (int i = 0; i < n; i++)
            //{
            //    matrix[i] = new int[n];
            //}
            //List<int[]> positions = new List<int[]>();
            //int top = 0, left = 0, count = 1;
            //while (n > 0)
            //{
            //    if (n == 1)
            //    {
            //        (positions as List<int[]>).Add(new int[] { top, left });
            //        break;
            //    }
            //    (positions as List<int[]>).AddRange(Enumerable.Range(left, n - 1).Select(i => new int[] { top, i }));
            //    (positions as List<int[]>).AddRange(Enumerable.Range(top, n - 1).Select(i => new int[] { i, (left + n - 1) }));
            //    (positions as List<int[]>).AddRange(Enumerable.Range(left + 1, n - 1).Reverse().Select(i => new int[] { (top + n - 1), i }));
            //    (positions as List<int[]>).AddRange(Enumerable.Range(top + 1, n - 1).Reverse().Select(i => new int[] { i, left }));
            //    top++;
            //    left++;
            //    n -= 2;
            //}

            //Array.ForEach(positions.ToArray(), i => {
            //    matrix[i[0]][i[1]] = count;
            //    count++;
            //    Console.WriteLine($"[{i[0]},{i[1]}] - {matrix[i[0]][i[1]]}");
            //});


            //int[][] matrix2 = new int[2][];
            //IList<int[]> resti = new List<int[]>();
            //int width =3, height = 3, top = 1, left = 1;
            //(resti as List<int[]>).AddRange(Enumerable.Range(left, width - 1).Select(i => new int[] { top, i }).ToArray());
            //(resti as List<int[]>).AddRange(Enumerable.Range(top, height - 1).Select(i => new int[] { i, (left + width - 1) }).ToArray());
            //(resti as List<int[]>).AddRange(Enumerable.Range(left + 1, width - 1).Reverse().Select(i => new int[] { (top + height - 1), i }).ToArray());
            //(resti as List<int[]>).AddRange(Enumerable.Range(top + 1, height - 1).Reverse().Select(i => new int[] { i, left }).ToArray());
            //var qwe = resti.Select(i => matrix2[i[0]][i[1]]).ToList();

            //ListNode head = new ListNode(1);
            //ListNode node1 = new ListNode(4);
            //ListNode node2 = new ListNode(3);
            //ListNode node3 = new ListNode(2);
            //ListNode node4 = new ListNode(5);
            //ListNode node5 = new ListNode(2);
            //head.next = node1;
            //node1.next = node2;
            //node2.next = node3;
            //node3.next = node4;
            //node4.next = node5;

            //var head2 = (new partition_list()).Partition(head, 3);
            var data1 = (new permutation_sequenceV2()).GetPermutation(4, 10);

            int[] arr1 = new int[] { 0, 0, 3, 0, 0, 0, 0, 0, 0 };
            int[] arr2 = new int[] { -1, 1, 1, 1, 2, 3 };

            (new merge_sorted_array()).MergeV2(arr1, 3, arr2, 6);
            var car = (new CarPlateNumber()).Generate();
            int rob = (new house_robber_ii()).Rob(new int[] { 1, 2, 1, 1 });

            int[] arr       = Enumerable.Repeat(int.MinValue, 4).ToArray();
            var   perm      = (new permutations()).Permute(new int[] { 1, 1, 2 });
            var   solutions = (new n_queens()).SolveNQueens(4);

            IList <IList <string> > list2 = new List <IList <string> >();

            for (int i = 0; i < 8; i++)
            {
                list2.Add(Enumerable.Repeat <string>(".", 8).ToList());
            }
            list2[0][0] = "change";


            Dictionary <string, IList <int> > res3 = new Dictionary <string, IList <int> >();
            var res4 = res3.Values.ToList();

            var res = combination_sum.Answer(new int[] { 2, 3, 4 }, 24);

            List <char[]> board = new List <char[]>();

            board.Add(new char[] { '5', '3', '.', '.', '7', '.', '.', '.', '.' });
            board.Add(new char[] { '6', '.', '.', '1', '9', '5', '.', '.', '.' });
            board.Add(new char[] { '.', '9', '8', '.', '.', '.', '.', '6', '.' });
            board.Add(new char[] { '8', '.', '.', '.', '6', '.', '.', '.', '3' });
            board.Add(new char[] { '4', '.', '.', '8', '.', '3', '.', '.', '1' });
            board.Add(new char[] { '7', '.', '.', '.', '2', '.', '.', '.', '6' });
            board.Add(new char[] { '.', '6', '.', '.', '.', '.', '2', '8', '.' });
            board.Add(new char[] { '.', '.', '.', '4', '1', '9', '.', '.', '5' });
            board.Add(new char[] { '.', '.', '.', '.', '8', '.', '.', '7', '9' });

            var valid = valid_sudoku.Answer(board.ToArray());


            var answer = find_first_and_last_position_of_element_in_sorted_array.Answer(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 9);

            var ans3 = Problem3.Answer(new int[, ] {
                { 1, 3, 1, 2, 9, 4 }, { 1, 5, 1, 2, 6, 1 }, { 4, 2, 1, 2, 8, 3 }, { 6, 1, 4, 3, 1, 1 }
            });
            var ans32 = Problem3.ImporvedAnswer(new int[, ] {
                { 1, 3, 1, 2, 9, 4 }, { 1, 5, 1, 2, 6, 1 }, { 4, 2, 1, 2, 8, 3 }, { 6, 1, 4, 3, 1, 1 }
            });
            var ans  = Problem2.Answer(4, 6);
            var ans2 = Problem2.ImporvedAnswer(4, 6);


            var answer1  = Problem1.Answer1(10);
            var answer11 = Problem1.ImprovedAnswer1(10);
            var answer2  = Problem1.Answer2(10);
            var result   = generate_parentheses.GenerateParenthesis(4);

            foreach (var s in result)
            {
                Console.WriteLine(s);
            }

            //ThreeSumClosestHelper threeSumClostest = new ThreeSumClosestHelper();
            //var result = threeSumClostest.ThreeSumClosest(new int[] { -1, 2, 1, 4 }, 1);

            //var result = ThreeSum.Answer(new int[] { -1, 0, 1, 2, -1, -4, 3, 4, -5, 6 });
            //var result = ThreeSum.Answer(new int[] { 0,0,0,0,0});
            //foreach (var s in result)
            //{
            //    Console.WriteLine(string.Join(" ", s));
            //}

            //var result = LetterCombinationsOfAPhoneNumber.Answer("789");
            //foreach (var s in result)
            //{
            //    Console.WriteLine(s);
            //}

            //var result = DfsPermutation.Make(new int[] { 1,3,6,2});

            //DfsPermutationGenerator dfs = new DfsPermutationGenerator(9);
            //dfs.Make();

            //DfsSolution.subsets(new int[] { 1,2,3});

            RomanToInteger.RomanToInt("MCMXCIV");
            StringtoInteger.Answer("-91283472332");

            LeetCodeTesting();

            QuickSortTest();
            BinaryHeapTest();
            BinarySearchTreeTest();
            BinarySearchTreeMirrorTest();
            AVLTreeTest();
            RedBlackTreeTest();
            SplayTreeTest();
            SegmentTreeTest_Max();
            SegmentTreeTest_Min();
            SegmentTreeTest_Sum();
            BTreeTest();

            Console.ReadLine();
        }
 public static void Main(string[] args)
 {
     int[] array = new int[] { 3, 4, 2, 1, 6, 5, 7, 8, 10, 9 };
     Console.Write("value at index 5 is : " + QuickSelect.get(array, 5));
 }